73d511074abd13cd6a4b700c4f329959fffda829
[platform/upstream/v8.git] / src / runtime / runtime-i18n.cc
1 // 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
5
6 #ifdef V8_I18N_SUPPORT
7 #include "src/runtime/runtime-utils.h"
8
9 #include "src/api.h"
10 #include "src/api-natives.h"
11 #include "src/arguments.h"
12 #include "src/factory.h"
13 #include "src/i18n.h"
14 #include "src/messages.h"
15
16 #include "unicode/brkiter.h"
17 #include "unicode/calendar.h"
18 #include "unicode/coll.h"
19 #include "unicode/curramt.h"
20 #include "unicode/datefmt.h"
21 #include "unicode/dcfmtsym.h"
22 #include "unicode/decimfmt.h"
23 #include "unicode/dtfmtsym.h"
24 #include "unicode/dtptngen.h"
25 #include "unicode/locid.h"
26 #include "unicode/numfmt.h"
27 #include "unicode/numsys.h"
28 #include "unicode/rbbi.h"
29 #include "unicode/smpdtfmt.h"
30 #include "unicode/timezone.h"
31 #include "unicode/uchar.h"
32 #include "unicode/ucol.h"
33 #include "unicode/ucurr.h"
34 #include "unicode/uloc.h"
35 #include "unicode/unum.h"
36 #include "unicode/uversion.h"
37
38
39 namespace v8 {
40 namespace internal {
41
42 RUNTIME_FUNCTION(Runtime_CanonicalizeLanguageTag) {
43   HandleScope scope(isolate);
44   Factory* factory = isolate->factory();
45
46   DCHECK(args.length() == 1);
47   CONVERT_ARG_HANDLE_CHECKED(String, locale_id_str, 0);
48
49   v8::String::Utf8Value locale_id(v8::Utils::ToLocal(locale_id_str));
50
51   // Return value which denotes invalid language tag.
52   const char* const kInvalidTag = "invalid-tag";
53
54   UErrorCode error = U_ZERO_ERROR;
55   char icu_result[ULOC_FULLNAME_CAPACITY];
56   int icu_length = 0;
57
58   uloc_forLanguageTag(*locale_id, icu_result, ULOC_FULLNAME_CAPACITY,
59                       &icu_length, &error);
60   if (U_FAILURE(error) || icu_length == 0) {
61     return *factory->NewStringFromAsciiChecked(kInvalidTag);
62   }
63
64   char result[ULOC_FULLNAME_CAPACITY];
65
66   // Force strict BCP47 rules.
67   uloc_toLanguageTag(icu_result, result, ULOC_FULLNAME_CAPACITY, TRUE, &error);
68
69   if (U_FAILURE(error)) {
70     return *factory->NewStringFromAsciiChecked(kInvalidTag);
71   }
72
73   return *factory->NewStringFromAsciiChecked(result);
74 }
75
76
77 RUNTIME_FUNCTION(Runtime_AvailableLocalesOf) {
78   HandleScope scope(isolate);
79   Factory* factory = isolate->factory();
80
81   DCHECK(args.length() == 1);
82   CONVERT_ARG_HANDLE_CHECKED(String, service, 0);
83
84   const icu::Locale* available_locales = NULL;
85   int32_t count = 0;
86
87   if (service->IsUtf8EqualTo(CStrVector("collator"))) {
88     available_locales = icu::Collator::getAvailableLocales(count);
89   } else if (service->IsUtf8EqualTo(CStrVector("numberformat"))) {
90     available_locales = icu::NumberFormat::getAvailableLocales(count);
91   } else if (service->IsUtf8EqualTo(CStrVector("dateformat"))) {
92     available_locales = icu::DateFormat::getAvailableLocales(count);
93   } else if (service->IsUtf8EqualTo(CStrVector("breakiterator"))) {
94     available_locales = icu::BreakIterator::getAvailableLocales(count);
95   }
96
97   UErrorCode error = U_ZERO_ERROR;
98   char result[ULOC_FULLNAME_CAPACITY];
99   Handle<JSObject> locales = factory->NewJSObject(isolate->object_function());
100
101   for (int32_t i = 0; i < count; ++i) {
102     const char* icu_name = available_locales[i].getName();
103
104     error = U_ZERO_ERROR;
105     // No need to force strict BCP47 rules.
106     uloc_toLanguageTag(icu_name, result, ULOC_FULLNAME_CAPACITY, FALSE, &error);
107     if (U_FAILURE(error)) {
108       // This shouldn't happen, but lets not break the user.
109       continue;
110     }
111
112     RETURN_FAILURE_ON_EXCEPTION(
113         isolate, JSObject::SetOwnPropertyIgnoreAttributes(
114                      locales, factory->NewStringFromAsciiChecked(result),
115                      factory->NewNumber(i), NONE));
116   }
117
118   return *locales;
119 }
120
121
122 RUNTIME_FUNCTION(Runtime_GetDefaultICULocale) {
123   HandleScope scope(isolate);
124   Factory* factory = isolate->factory();
125
126   DCHECK(args.length() == 0);
127
128   icu::Locale default_locale;
129
130   // Set the locale
131   char result[ULOC_FULLNAME_CAPACITY];
132   UErrorCode status = U_ZERO_ERROR;
133   uloc_toLanguageTag(default_locale.getName(), result, ULOC_FULLNAME_CAPACITY,
134                      FALSE, &status);
135   if (U_SUCCESS(status)) {
136     return *factory->NewStringFromAsciiChecked(result);
137   }
138
139   return *factory->NewStringFromStaticChars("und");
140 }
141
142
143 RUNTIME_FUNCTION(Runtime_GetLanguageTagVariants) {
144   HandleScope scope(isolate);
145   Factory* factory = isolate->factory();
146
147   DCHECK(args.length() == 1);
148
149   CONVERT_ARG_HANDLE_CHECKED(JSArray, input, 0);
150
151   uint32_t length = static_cast<uint32_t>(input->length()->Number());
152   // Set some limit to prevent fuzz tests from going OOM.
153   // Can be bumped when callers' requirements change.
154   RUNTIME_ASSERT(length < 100);
155   Handle<FixedArray> output = factory->NewFixedArray(length);
156   Handle<Name> maximized = factory->NewStringFromStaticChars("maximized");
157   Handle<Name> base = factory->NewStringFromStaticChars("base");
158   for (unsigned int i = 0; i < length; ++i) {
159     Handle<Object> locale_id;
160     ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, locale_id,
161                                        Object::GetElement(isolate, input, i));
162     if (!locale_id->IsString()) {
163       return isolate->Throw(*factory->illegal_argument_string());
164     }
165
166     v8::String::Utf8Value utf8_locale_id(
167         v8::Utils::ToLocal(Handle<String>::cast(locale_id)));
168
169     UErrorCode error = U_ZERO_ERROR;
170
171     // Convert from BCP47 to ICU format.
172     // de-DE-u-co-phonebk -> de_DE@collation=phonebook
173     char icu_locale[ULOC_FULLNAME_CAPACITY];
174     int icu_locale_length = 0;
175     uloc_forLanguageTag(*utf8_locale_id, icu_locale, ULOC_FULLNAME_CAPACITY,
176                         &icu_locale_length, &error);
177     if (U_FAILURE(error) || icu_locale_length == 0) {
178       return isolate->Throw(*factory->illegal_argument_string());
179     }
180
181     // Maximize the locale.
182     // de_DE@collation=phonebook -> de_Latn_DE@collation=phonebook
183     char icu_max_locale[ULOC_FULLNAME_CAPACITY];
184     uloc_addLikelySubtags(icu_locale, icu_max_locale, ULOC_FULLNAME_CAPACITY,
185                           &error);
186
187     // Remove extensions from maximized locale.
188     // de_Latn_DE@collation=phonebook -> de_Latn_DE
189     char icu_base_max_locale[ULOC_FULLNAME_CAPACITY];
190     uloc_getBaseName(icu_max_locale, icu_base_max_locale,
191                      ULOC_FULLNAME_CAPACITY, &error);
192
193     // Get original name without extensions.
194     // de_DE@collation=phonebook -> de_DE
195     char icu_base_locale[ULOC_FULLNAME_CAPACITY];
196     uloc_getBaseName(icu_locale, icu_base_locale, ULOC_FULLNAME_CAPACITY,
197                      &error);
198
199     // Convert from ICU locale format to BCP47 format.
200     // de_Latn_DE -> de-Latn-DE
201     char base_max_locale[ULOC_FULLNAME_CAPACITY];
202     uloc_toLanguageTag(icu_base_max_locale, base_max_locale,
203                        ULOC_FULLNAME_CAPACITY, FALSE, &error);
204
205     // de_DE -> de-DE
206     char base_locale[ULOC_FULLNAME_CAPACITY];
207     uloc_toLanguageTag(icu_base_locale, base_locale, ULOC_FULLNAME_CAPACITY,
208                        FALSE, &error);
209
210     if (U_FAILURE(error)) {
211       return isolate->Throw(*factory->illegal_argument_string());
212     }
213
214     Handle<JSObject> result = factory->NewJSObject(isolate->object_function());
215     Handle<String> value = factory->NewStringFromAsciiChecked(base_max_locale);
216     JSObject::AddProperty(result, maximized, value, NONE);
217     value = factory->NewStringFromAsciiChecked(base_locale);
218     JSObject::AddProperty(result, base, value, NONE);
219     output->set(i, *result);
220   }
221
222   Handle<JSArray> result = factory->NewJSArrayWithElements(output);
223   result->set_length(Smi::FromInt(length));
224   return *result;
225 }
226
227
228 RUNTIME_FUNCTION(Runtime_IsInitializedIntlObject) {
229   HandleScope scope(isolate);
230
231   DCHECK(args.length() == 1);
232
233   CONVERT_ARG_HANDLE_CHECKED(Object, input, 0);
234
235   if (!input->IsJSObject()) return isolate->heap()->false_value();
236   Handle<JSObject> obj = Handle<JSObject>::cast(input);
237
238   Handle<Symbol> marker = isolate->factory()->intl_initialized_marker_symbol();
239   Handle<Object> tag = JSReceiver::GetDataProperty(obj, marker);
240   return isolate->heap()->ToBoolean(!tag->IsUndefined());
241 }
242
243
244 RUNTIME_FUNCTION(Runtime_IsInitializedIntlObjectOfType) {
245   HandleScope scope(isolate);
246
247   DCHECK(args.length() == 2);
248
249   CONVERT_ARG_HANDLE_CHECKED(Object, input, 0);
250   CONVERT_ARG_HANDLE_CHECKED(String, expected_type, 1);
251
252   if (!input->IsJSObject()) return isolate->heap()->false_value();
253   Handle<JSObject> obj = Handle<JSObject>::cast(input);
254
255   Handle<Symbol> marker = isolate->factory()->intl_initialized_marker_symbol();
256   Handle<Object> tag = JSReceiver::GetDataProperty(obj, marker);
257   return isolate->heap()->ToBoolean(tag->IsString() &&
258                                     String::cast(*tag)->Equals(*expected_type));
259 }
260
261
262 RUNTIME_FUNCTION(Runtime_MarkAsInitializedIntlObjectOfType) {
263   HandleScope scope(isolate);
264
265   DCHECK(args.length() == 3);
266
267   CONVERT_ARG_HANDLE_CHECKED(JSObject, input, 0);
268   CONVERT_ARG_HANDLE_CHECKED(String, type, 1);
269   CONVERT_ARG_HANDLE_CHECKED(JSObject, impl, 2);
270
271   Handle<Symbol> marker = isolate->factory()->intl_initialized_marker_symbol();
272   JSObject::SetProperty(input, marker, type, STRICT).Assert();
273
274   marker = isolate->factory()->intl_impl_object_symbol();
275   JSObject::SetProperty(input, marker, impl, STRICT).Assert();
276
277   return isolate->heap()->undefined_value();
278 }
279
280
281 RUNTIME_FUNCTION(Runtime_GetImplFromInitializedIntlObject) {
282   HandleScope scope(isolate);
283
284   DCHECK(args.length() == 1);
285
286   CONVERT_ARG_HANDLE_CHECKED(JSObject, input, 0);
287
288   if (!input->IsJSObject()) {
289     THROW_NEW_ERROR_RETURN_FAILURE(
290         isolate, NewTypeError(MessageTemplate::kNotIntlObject, input));
291   }
292
293   Handle<JSObject> obj = Handle<JSObject>::cast(input);
294
295   Handle<Symbol> marker = isolate->factory()->intl_impl_object_symbol();
296
297   Handle<Object> impl = JSReceiver::GetDataProperty(obj, marker);
298   if (impl->IsTheHole()) {
299     THROW_NEW_ERROR_RETURN_FAILURE(
300         isolate, NewTypeError(MessageTemplate::kNotIntlObject, obj));
301   }
302   return *impl;
303 }
304
305
306 RUNTIME_FUNCTION(Runtime_CreateDateTimeFormat) {
307   HandleScope scope(isolate);
308
309   DCHECK(args.length() == 3);
310
311   CONVERT_ARG_HANDLE_CHECKED(String, locale, 0);
312   CONVERT_ARG_HANDLE_CHECKED(JSObject, options, 1);
313   CONVERT_ARG_HANDLE_CHECKED(JSObject, resolved, 2);
314
315   Handle<ObjectTemplateInfo> date_format_template = I18N::GetTemplate(isolate);
316
317   // Create an empty object wrapper.
318   Handle<JSObject> local_object;
319   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
320       isolate, local_object,
321       ApiNatives::InstantiateObject(date_format_template));
322
323   // Set date time formatter as internal field of the resulting JS object.
324   icu::SimpleDateFormat* date_format =
325       DateFormat::InitializeDateTimeFormat(isolate, locale, options, resolved);
326
327   if (!date_format) return isolate->ThrowIllegalOperation();
328
329   local_object->SetInternalField(0, reinterpret_cast<Smi*>(date_format));
330
331   Factory* factory = isolate->factory();
332   Handle<String> key = factory->NewStringFromStaticChars("dateFormat");
333   Handle<String> value = factory->NewStringFromStaticChars("valid");
334   JSObject::AddProperty(local_object, key, value, NONE);
335
336   // Make object handle weak so we can delete the data format once GC kicks in.
337   Handle<Object> wrapper = isolate->global_handles()->Create(*local_object);
338   GlobalHandles::MakeWeak(wrapper.location(),
339                           reinterpret_cast<void*>(wrapper.location()),
340                           DateFormat::DeleteDateFormat);
341   return *local_object;
342 }
343
344
345 RUNTIME_FUNCTION(Runtime_InternalDateFormat) {
346   HandleScope scope(isolate);
347
348   DCHECK(args.length() == 2);
349
350   CONVERT_ARG_HANDLE_CHECKED(JSObject, date_format_holder, 0);
351   CONVERT_ARG_HANDLE_CHECKED(JSDate, date, 1);
352
353   Handle<Object> value;
354   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, value,
355                                      Execution::ToNumber(isolate, date));
356
357   icu::SimpleDateFormat* date_format =
358       DateFormat::UnpackDateFormat(isolate, date_format_holder);
359   if (!date_format) return isolate->ThrowIllegalOperation();
360
361   icu::UnicodeString result;
362   date_format->format(value->Number(), result);
363
364   Handle<String> result_str;
365   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
366       isolate, result_str,
367       isolate->factory()->NewStringFromTwoByte(Vector<const uint16_t>(
368           reinterpret_cast<const uint16_t*>(result.getBuffer()),
369           result.length())));
370   return *result_str;
371 }
372
373
374 RUNTIME_FUNCTION(Runtime_InternalDateParse) {
375   HandleScope scope(isolate);
376
377   DCHECK(args.length() == 2);
378
379   CONVERT_ARG_HANDLE_CHECKED(JSObject, date_format_holder, 0);
380   CONVERT_ARG_HANDLE_CHECKED(String, date_string, 1);
381
382   v8::String::Utf8Value utf8_date(v8::Utils::ToLocal(date_string));
383   icu::UnicodeString u_date(icu::UnicodeString::fromUTF8(*utf8_date));
384   icu::SimpleDateFormat* date_format =
385       DateFormat::UnpackDateFormat(isolate, date_format_holder);
386   if (!date_format) return isolate->ThrowIllegalOperation();
387
388   UErrorCode status = U_ZERO_ERROR;
389   UDate date = date_format->parse(u_date, status);
390   if (U_FAILURE(status)) return isolate->heap()->undefined_value();
391
392   Handle<Object> result;
393   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
394       isolate, result, Execution::NewDate(isolate, static_cast<double>(date)));
395   DCHECK(result->IsJSDate());
396   return *result;
397 }
398
399
400 RUNTIME_FUNCTION(Runtime_CreateNumberFormat) {
401   HandleScope scope(isolate);
402
403   DCHECK(args.length() == 3);
404
405   CONVERT_ARG_HANDLE_CHECKED(String, locale, 0);
406   CONVERT_ARG_HANDLE_CHECKED(JSObject, options, 1);
407   CONVERT_ARG_HANDLE_CHECKED(JSObject, resolved, 2);
408
409   Handle<ObjectTemplateInfo> number_format_template =
410       I18N::GetTemplate(isolate);
411
412   // Create an empty object wrapper.
413   Handle<JSObject> local_object;
414   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
415       isolate, local_object,
416       ApiNatives::InstantiateObject(number_format_template));
417
418   // Set number formatter as internal field of the resulting JS object.
419   icu::DecimalFormat* number_format =
420       NumberFormat::InitializeNumberFormat(isolate, locale, options, resolved);
421
422   if (!number_format) return isolate->ThrowIllegalOperation();
423
424   local_object->SetInternalField(0, reinterpret_cast<Smi*>(number_format));
425
426   Factory* factory = isolate->factory();
427   Handle<String> key = factory->NewStringFromStaticChars("numberFormat");
428   Handle<String> value = factory->NewStringFromStaticChars("valid");
429   JSObject::AddProperty(local_object, key, value, NONE);
430
431   Handle<Object> wrapper = isolate->global_handles()->Create(*local_object);
432   GlobalHandles::MakeWeak(wrapper.location(),
433                           reinterpret_cast<void*>(wrapper.location()),
434                           NumberFormat::DeleteNumberFormat);
435   return *local_object;
436 }
437
438
439 RUNTIME_FUNCTION(Runtime_InternalNumberFormat) {
440   HandleScope scope(isolate);
441
442   DCHECK(args.length() == 2);
443
444   CONVERT_ARG_HANDLE_CHECKED(JSObject, number_format_holder, 0);
445   CONVERT_ARG_HANDLE_CHECKED(Object, number, 1);
446
447   Handle<Object> value;
448   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, value,
449                                      Execution::ToNumber(isolate, number));
450
451   icu::DecimalFormat* number_format =
452       NumberFormat::UnpackNumberFormat(isolate, number_format_holder);
453   if (!number_format) return isolate->ThrowIllegalOperation();
454
455   icu::UnicodeString result;
456   number_format->format(value->Number(), result);
457
458   Handle<String> result_str;
459   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
460       isolate, result_str,
461       isolate->factory()->NewStringFromTwoByte(Vector<const uint16_t>(
462           reinterpret_cast<const uint16_t*>(result.getBuffer()),
463           result.length())));
464   return *result_str;
465 }
466
467
468 RUNTIME_FUNCTION(Runtime_InternalNumberParse) {
469   HandleScope scope(isolate);
470
471   DCHECK(args.length() == 2);
472
473   CONVERT_ARG_HANDLE_CHECKED(JSObject, number_format_holder, 0);
474   CONVERT_ARG_HANDLE_CHECKED(String, number_string, 1);
475
476   v8::String::Utf8Value utf8_number(v8::Utils::ToLocal(number_string));
477   icu::UnicodeString u_number(icu::UnicodeString::fromUTF8(*utf8_number));
478   icu::DecimalFormat* number_format =
479       NumberFormat::UnpackNumberFormat(isolate, number_format_holder);
480   if (!number_format) return isolate->ThrowIllegalOperation();
481
482   UErrorCode status = U_ZERO_ERROR;
483   icu::Formattable result;
484   // ICU 4.6 doesn't support parseCurrency call. We need to wait for ICU49
485   // to be part of Chrome.
486   // TODO(cira): Include currency parsing code using parseCurrency call.
487   // We need to check if the formatter parses all currencies or only the
488   // one it was constructed with (it will impact the API - how to return ISO
489   // code and the value).
490   number_format->parse(u_number, result, status);
491   if (U_FAILURE(status)) return isolate->heap()->undefined_value();
492
493   switch (result.getType()) {
494     case icu::Formattable::kDouble:
495       return *isolate->factory()->NewNumber(result.getDouble());
496     case icu::Formattable::kLong:
497       return *isolate->factory()->NewNumberFromInt(result.getLong());
498     case icu::Formattable::kInt64:
499       return *isolate->factory()->NewNumber(
500           static_cast<double>(result.getInt64()));
501     default:
502       return isolate->heap()->undefined_value();
503   }
504 }
505
506
507 RUNTIME_FUNCTION(Runtime_CreateCollator) {
508   HandleScope scope(isolate);
509
510   DCHECK(args.length() == 3);
511
512   CONVERT_ARG_HANDLE_CHECKED(String, locale, 0);
513   CONVERT_ARG_HANDLE_CHECKED(JSObject, options, 1);
514   CONVERT_ARG_HANDLE_CHECKED(JSObject, resolved, 2);
515
516   Handle<ObjectTemplateInfo> collator_template = I18N::GetTemplate(isolate);
517
518   // Create an empty object wrapper.
519   Handle<JSObject> local_object;
520   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
521       isolate, local_object, ApiNatives::InstantiateObject(collator_template));
522
523   // Set collator as internal field of the resulting JS object.
524   icu::Collator* collator =
525       Collator::InitializeCollator(isolate, locale, options, resolved);
526
527   if (!collator) return isolate->ThrowIllegalOperation();
528
529   local_object->SetInternalField(0, reinterpret_cast<Smi*>(collator));
530
531   Factory* factory = isolate->factory();
532   Handle<String> key = factory->NewStringFromStaticChars("collator");
533   Handle<String> value = factory->NewStringFromStaticChars("valid");
534   JSObject::AddProperty(local_object, key, value, NONE);
535
536   Handle<Object> wrapper = isolate->global_handles()->Create(*local_object);
537   GlobalHandles::MakeWeak(wrapper.location(),
538                           reinterpret_cast<void*>(wrapper.location()),
539                           Collator::DeleteCollator);
540   return *local_object;
541 }
542
543
544 RUNTIME_FUNCTION(Runtime_InternalCompare) {
545   HandleScope scope(isolate);
546
547   DCHECK(args.length() == 3);
548
549   CONVERT_ARG_HANDLE_CHECKED(JSObject, collator_holder, 0);
550   CONVERT_ARG_HANDLE_CHECKED(String, string1, 1);
551   CONVERT_ARG_HANDLE_CHECKED(String, string2, 2);
552
553   icu::Collator* collator = Collator::UnpackCollator(isolate, collator_holder);
554   if (!collator) return isolate->ThrowIllegalOperation();
555
556   v8::String::Value string_value1(v8::Utils::ToLocal(string1));
557   v8::String::Value string_value2(v8::Utils::ToLocal(string2));
558   const UChar* u_string1 = reinterpret_cast<const UChar*>(*string_value1);
559   const UChar* u_string2 = reinterpret_cast<const UChar*>(*string_value2);
560   UErrorCode status = U_ZERO_ERROR;
561   UCollationResult result =
562       collator->compare(u_string1, string_value1.length(), u_string2,
563                         string_value2.length(), status);
564   if (U_FAILURE(status)) return isolate->ThrowIllegalOperation();
565
566   return *isolate->factory()->NewNumberFromInt(result);
567 }
568
569
570 RUNTIME_FUNCTION(Runtime_StringNormalize) {
571   HandleScope scope(isolate);
572   static const UNormalizationMode normalizationForms[] = {
573       UNORM_NFC, UNORM_NFD, UNORM_NFKC, UNORM_NFKD};
574
575   DCHECK(args.length() == 2);
576
577   CONVERT_ARG_HANDLE_CHECKED(String, stringValue, 0);
578   CONVERT_NUMBER_CHECKED(int, form_id, Int32, args[1]);
579   RUNTIME_ASSERT(form_id >= 0 &&
580                  static_cast<size_t>(form_id) < arraysize(normalizationForms));
581
582   v8::String::Value string_value(v8::Utils::ToLocal(stringValue));
583   const UChar* u_value = reinterpret_cast<const UChar*>(*string_value);
584
585   // TODO(mnita): check Normalizer2 (not available in ICU 46)
586   UErrorCode status = U_ZERO_ERROR;
587   icu::UnicodeString result;
588   icu::Normalizer::normalize(u_value, normalizationForms[form_id], 0, result,
589                              status);
590   if (U_FAILURE(status)) {
591     return isolate->heap()->undefined_value();
592   }
593
594   Handle<String> result_str;
595   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
596       isolate, result_str,
597       isolate->factory()->NewStringFromTwoByte(Vector<const uint16_t>(
598           reinterpret_cast<const uint16_t*>(result.getBuffer()),
599           result.length())));
600   return *result_str;
601 }
602
603
604 RUNTIME_FUNCTION(Runtime_CreateBreakIterator) {
605   HandleScope scope(isolate);
606
607   DCHECK(args.length() == 3);
608
609   CONVERT_ARG_HANDLE_CHECKED(String, locale, 0);
610   CONVERT_ARG_HANDLE_CHECKED(JSObject, options, 1);
611   CONVERT_ARG_HANDLE_CHECKED(JSObject, resolved, 2);
612
613   Handle<ObjectTemplateInfo> break_iterator_template =
614       I18N::GetTemplate2(isolate);
615
616   // Create an empty object wrapper.
617   Handle<JSObject> local_object;
618   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
619       isolate, local_object,
620       ApiNatives::InstantiateObject(break_iterator_template));
621
622   // Set break iterator as internal field of the resulting JS object.
623   icu::BreakIterator* break_iterator = BreakIterator::InitializeBreakIterator(
624       isolate, locale, options, resolved);
625
626   if (!break_iterator) return isolate->ThrowIllegalOperation();
627
628   local_object->SetInternalField(0, reinterpret_cast<Smi*>(break_iterator));
629   // Make sure that the pointer to adopted text is NULL.
630   local_object->SetInternalField(1, static_cast<Smi*>(nullptr));
631
632   Factory* factory = isolate->factory();
633   Handle<String> key = factory->NewStringFromStaticChars("breakIterator");
634   Handle<String> value = factory->NewStringFromStaticChars("valid");
635   JSObject::AddProperty(local_object, key, value, NONE);
636
637   // Make object handle weak so we can delete the break iterator once GC kicks
638   // in.
639   Handle<Object> wrapper = isolate->global_handles()->Create(*local_object);
640   GlobalHandles::MakeWeak(wrapper.location(),
641                           reinterpret_cast<void*>(wrapper.location()),
642                           BreakIterator::DeleteBreakIterator);
643   return *local_object;
644 }
645
646
647 RUNTIME_FUNCTION(Runtime_BreakIteratorAdoptText) {
648   HandleScope scope(isolate);
649
650   DCHECK(args.length() == 2);
651
652   CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
653   CONVERT_ARG_HANDLE_CHECKED(String, text, 1);
654
655   icu::BreakIterator* break_iterator =
656       BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
657   if (!break_iterator) return isolate->ThrowIllegalOperation();
658
659   icu::UnicodeString* u_text = reinterpret_cast<icu::UnicodeString*>(
660       break_iterator_holder->GetInternalField(1));
661   delete u_text;
662
663   v8::String::Value text_value(v8::Utils::ToLocal(text));
664   u_text = new icu::UnicodeString(reinterpret_cast<const UChar*>(*text_value),
665                                   text_value.length());
666   break_iterator_holder->SetInternalField(1, reinterpret_cast<Smi*>(u_text));
667
668   break_iterator->setText(*u_text);
669
670   return isolate->heap()->undefined_value();
671 }
672
673
674 RUNTIME_FUNCTION(Runtime_BreakIteratorFirst) {
675   HandleScope scope(isolate);
676
677   DCHECK(args.length() == 1);
678
679   CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
680
681   icu::BreakIterator* break_iterator =
682       BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
683   if (!break_iterator) return isolate->ThrowIllegalOperation();
684
685   return *isolate->factory()->NewNumberFromInt(break_iterator->first());
686 }
687
688
689 RUNTIME_FUNCTION(Runtime_BreakIteratorNext) {
690   HandleScope scope(isolate);
691
692   DCHECK(args.length() == 1);
693
694   CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
695
696   icu::BreakIterator* break_iterator =
697       BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
698   if (!break_iterator) return isolate->ThrowIllegalOperation();
699
700   return *isolate->factory()->NewNumberFromInt(break_iterator->next());
701 }
702
703
704 RUNTIME_FUNCTION(Runtime_BreakIteratorCurrent) {
705   HandleScope scope(isolate);
706
707   DCHECK(args.length() == 1);
708
709   CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
710
711   icu::BreakIterator* break_iterator =
712       BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
713   if (!break_iterator) return isolate->ThrowIllegalOperation();
714
715   return *isolate->factory()->NewNumberFromInt(break_iterator->current());
716 }
717
718
719 RUNTIME_FUNCTION(Runtime_BreakIteratorBreakType) {
720   HandleScope scope(isolate);
721
722   DCHECK(args.length() == 1);
723
724   CONVERT_ARG_HANDLE_CHECKED(JSObject, break_iterator_holder, 0);
725
726   icu::BreakIterator* break_iterator =
727       BreakIterator::UnpackBreakIterator(isolate, break_iterator_holder);
728   if (!break_iterator) return isolate->ThrowIllegalOperation();
729
730   // TODO(cira): Remove cast once ICU fixes base BreakIterator class.
731   icu::RuleBasedBreakIterator* rule_based_iterator =
732       static_cast<icu::RuleBasedBreakIterator*>(break_iterator);
733   int32_t status = rule_based_iterator->getRuleStatus();
734   // Keep return values in sync with JavaScript BreakType enum.
735   if (status >= UBRK_WORD_NONE && status < UBRK_WORD_NONE_LIMIT) {
736     return *isolate->factory()->NewStringFromStaticChars("none");
737   } else if (status >= UBRK_WORD_NUMBER && status < UBRK_WORD_NUMBER_LIMIT) {
738     return *isolate->factory()->number_string();
739   } else if (status >= UBRK_WORD_LETTER && status < UBRK_WORD_LETTER_LIMIT) {
740     return *isolate->factory()->NewStringFromStaticChars("letter");
741   } else if (status >= UBRK_WORD_KANA && status < UBRK_WORD_KANA_LIMIT) {
742     return *isolate->factory()->NewStringFromStaticChars("kana");
743   } else if (status >= UBRK_WORD_IDEO && status < UBRK_WORD_IDEO_LIMIT) {
744     return *isolate->factory()->NewStringFromStaticChars("ideo");
745   } else {
746     return *isolate->factory()->NewStringFromStaticChars("unknown");
747   }
748 }
749 }  // namespace internal
750 }  // namespace v8
751
752 #endif  // V8_I18N_SUPPORT