CPP: Make r570 compile in Chromium.
[platform/upstream/libphonenumber.git] / cpp / src / phonenumbers / phonenumberutil.cc
1 // Copyright (C) 2009 The Libphonenumber Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Author: Shaopeng Jia
16 // Open-sourced by: Philippe Liard
17
18 #include "phonenumbers/phonenumberutil.h"
19
20 #include <string.h>
21 #include <algorithm>
22 #include <cctype>
23 #include <fstream>
24 #include <iostream>
25 #include <iterator>
26 #include <map>
27 #include <sstream>
28 #include <utility>
29 #include <vector>
30
31 #include <google/protobuf/message_lite.h>
32 #include <unicode/uchar.h>
33 #include <unicode/utf8.h>
34
35 #include "phonenumbers/asyoutypeformatter.h"
36 #include "phonenumbers/base/basictypes.h"
37 #include "phonenumbers/base/logging.h"
38 #include "phonenumbers/base/memory/singleton.h"
39 #include "phonenumbers/default_logger.h"
40 #include "phonenumbers/encoding_utils.h"
41 #include "phonenumbers/metadata.h"
42 #include "phonenumbers/normalize_utf8.h"
43 #include "phonenumbers/phonemetadata.pb.h"
44 #include "phonenumbers/phonenumber.h"
45 #include "phonenumbers/phonenumber.pb.h"
46 #include "phonenumbers/regexp_adapter.h"
47 #include "phonenumbers/regexp_cache.h"
48 #include "phonenumbers/regexp_factory.h"
49 #include "phonenumbers/region_code.h"
50 #include "phonenumbers/stl_util.h"
51 #include "phonenumbers/stringutil.h"
52 #include "phonenumbers/utf/unicodetext.h"
53 #include "phonenumbers/utf/utf.h"
54
55 namespace i18n {
56 namespace phonenumbers {
57
58 using std::cerr;
59 using std::endl;
60 using std::ifstream;
61 using std::make_pair;
62 using std::sort;
63 using std::stringstream;
64
65 using google::protobuf::RepeatedPtrField;
66
67 // static
68 const char PhoneNumberUtil::kPlusChars[] = "+\xEF\xBC\x8B";  /* "++" */
69 // To find out the unicode code-point of the characters below in vim, highlight
70 // the character and type 'ga'. Note that the - is used to express ranges of
71 // full-width punctuation below, as well as being present in the expression
72 // itself. In emacs, you can use M-x unicode-what to query information about the
73 // unicode character.
74 // static
75 const char PhoneNumberUtil::kValidPunctuation[] =
76     /* "-x‐-―−ー--/  ­<U+200B><U+2060> ()()[].\\[\\]/~⁓∼" */
77     "-x\xE2\x80\x90-\xE2\x80\x95\xE2\x88\x92\xE3\x83\xBC\xEF\xBC\x8D-\xEF\xBC"
78     "\x8F \xC2\xA0\xC2\xAD\xE2\x80\x8B\xE2\x81\xA0\xE3\x80\x80()\xEF\xBC\x88"
79     "\xEF\xBC\x89\xEF\xBC\xBB\xEF\xBC\xBD.\\[\\]/~\xE2\x81\x93\xE2\x88\xBC";
80
81 // static
82 const char PhoneNumberUtil::kCaptureUpToSecondNumberStart[] = "(.*)[\\\\/] *x";
83
84 // static
85 const char PhoneNumberUtil::kRegionCodeForNonGeoEntity[] = "001";
86
87 namespace {
88
89 // The prefix that needs to be inserted in front of a Colombian landline
90 // number when dialed from a mobile phone in Colombia.
91 const char kColombiaMobileToFixedLinePrefix[] = "3";
92
93 // The kPlusSign signifies the international prefix.
94 const char kPlusSign[] = "+";
95
96 const char kStarSign[] = "*";
97
98 const char kRfc3966ExtnPrefix[] = ";ext=";
99 const char kRfc3966Prefix[] = "tel:";
100 const char kRfc3966PhoneContext[] = ";phone-context=";
101 const char kRfc3966IsdnSubaddress[] = ";isub=";
102
103 const char kDigits[] = "\\p{Nd}";
104 // We accept alpha characters in phone numbers, ASCII only. We store lower-case
105 // here only since our regular expressions are case-insensitive.
106 const char kValidAlpha[] = "a-z";
107
108 // Default extension prefix to use when formatting. This will be put in front of
109 // any extension component of the number, after the main national number is
110 // formatted. For example, if you wish the default extension formatting to be "
111 // extn: 3456", then you should specify " extn: " here as the default extension
112 // prefix. This can be overridden by region-specific preferences.
113 const char kDefaultExtnPrefix[] = " ext. ";
114
115 // One-character symbols that can be used to indicate an extension.
116 const char kSingleExtnSymbolsForMatching[] =
117     "x\xEF\xBD\x98#\xEF\xBC\x83~\xEF\xBD\x9E";
118
119 bool LoadCompiledInMetadata(PhoneMetadataCollection* metadata) {
120   if (!metadata->ParseFromArray(metadata_get(), metadata_size())) {
121     cerr << "Could not parse binary data." << endl;
122     return false;
123   }
124   return true;
125 }
126
127 // Returns a pointer to the description inside the metadata of the appropriate
128 // type.
129 const PhoneNumberDesc* GetNumberDescByType(
130     const PhoneMetadata& metadata,
131     PhoneNumberUtil::PhoneNumberType type) {
132   switch (type) {
133     case PhoneNumberUtil::PREMIUM_RATE:
134       return &metadata.premium_rate();
135     case PhoneNumberUtil::TOLL_FREE:
136       return &metadata.toll_free();
137     case PhoneNumberUtil::MOBILE:
138       return &metadata.mobile();
139     case PhoneNumberUtil::FIXED_LINE:
140     case PhoneNumberUtil::FIXED_LINE_OR_MOBILE:
141       return &metadata.fixed_line();
142     case PhoneNumberUtil::SHARED_COST:
143       return &metadata.shared_cost();
144     case PhoneNumberUtil::VOIP:
145       return &metadata.voip();
146     case PhoneNumberUtil::PERSONAL_NUMBER:
147       return &metadata.personal_number();
148     case PhoneNumberUtil::PAGER:
149       return &metadata.pager();
150     case PhoneNumberUtil::UAN:
151       return &metadata.uan();
152     case PhoneNumberUtil::VOICEMAIL:
153       return &metadata.voicemail();
154     default:
155       return &metadata.general_desc();
156   }
157 }
158
159 // A helper function that is used by Format and FormatByPattern.
160 void PrefixNumberWithCountryCallingCode(
161     int country_calling_code,
162     PhoneNumberUtil::PhoneNumberFormat number_format,
163     string* formatted_number) {
164   switch (number_format) {
165     case PhoneNumberUtil::E164:
166       formatted_number->insert(0, StrCat(kPlusSign, country_calling_code));
167       return;
168     case PhoneNumberUtil::INTERNATIONAL:
169       formatted_number->insert(0, StrCat(kPlusSign, country_calling_code, " "));
170       return;
171     case PhoneNumberUtil::RFC3966:
172       formatted_number->insert(0, StrCat(kRfc3966Prefix, kPlusSign,
173                                          country_calling_code, "-"));
174       return;
175     case PhoneNumberUtil::NATIONAL:
176     default:
177       // Do nothing.
178       return;
179   }
180 }
181
182 // Returns true when one national number is the suffix of the other or both are
183 // the same.
184 bool IsNationalNumberSuffixOfTheOther(const PhoneNumber& first_number,
185                                       const PhoneNumber& second_number) {
186   const string& first_number_national_number =
187     SimpleItoa(static_cast<uint64>(first_number.national_number()));
188   const string& second_number_national_number =
189     SimpleItoa(static_cast<uint64>(second_number.national_number()));
190   // Note that HasSuffixString returns true if the numbers are equal.
191   return HasSuffixString(first_number_national_number,
192                          second_number_national_number) ||
193          HasSuffixString(second_number_national_number,
194                          first_number_national_number);
195 }
196
197 bool IsNumberMatchingDesc(const string& national_number,
198                           const PhoneNumberDesc& number_desc,
199                           RegExpCache* regexp_cache) {
200   return regexp_cache->GetRegExp(number_desc.possible_number_pattern())
201              .FullMatch(national_number) &&
202          regexp_cache->GetRegExp(number_desc.national_number_pattern())
203              .FullMatch(national_number);
204 }
205
206 PhoneNumberUtil::PhoneNumberType GetNumberTypeHelper(
207     const string& national_number, const PhoneMetadata& metadata,
208     RegExpCache* regexp_cache) {
209   const PhoneNumberDesc& general_desc = metadata.general_desc();
210   if (!general_desc.has_national_number_pattern() ||
211       !IsNumberMatchingDesc(national_number, general_desc, regexp_cache)) {
212     VLOG(4) << "Number type unknown - doesn't match general national number"
213             << " pattern.";
214     return PhoneNumberUtil::UNKNOWN;
215   }
216   if (IsNumberMatchingDesc(national_number, metadata.premium_rate(),
217                            regexp_cache)) {
218     VLOG(4) << "Number is a premium number.";
219     return PhoneNumberUtil::PREMIUM_RATE;
220   }
221   if (IsNumberMatchingDesc(national_number, metadata.toll_free(),
222                            regexp_cache)) {
223     VLOG(4) << "Number is a toll-free number.";
224     return PhoneNumberUtil::TOLL_FREE;
225   }
226   if (IsNumberMatchingDesc(national_number, metadata.shared_cost(),
227                            regexp_cache)) {
228     VLOG(4) << "Number is a shared cost number.";
229     return PhoneNumberUtil::SHARED_COST;
230   }
231   if (IsNumberMatchingDesc(national_number, metadata.voip(), regexp_cache)) {
232     VLOG(4) << "Number is a VOIP (Voice over IP) number.";
233     return PhoneNumberUtil::VOIP;
234   }
235   if (IsNumberMatchingDesc(national_number, metadata.personal_number(),
236                            regexp_cache)) {
237     VLOG(4) << "Number is a personal number.";
238     return PhoneNumberUtil::PERSONAL_NUMBER;
239   }
240   if (IsNumberMatchingDesc(national_number, metadata.pager(), regexp_cache)) {
241     VLOG(4) << "Number is a pager number.";
242     return PhoneNumberUtil::PAGER;
243   }
244   if (IsNumberMatchingDesc(national_number, metadata.uan(), regexp_cache)) {
245     VLOG(4) << "Number is a UAN.";
246     return PhoneNumberUtil::UAN;
247   }
248   if (IsNumberMatchingDesc(national_number, metadata.voicemail(),
249                            regexp_cache)) {
250     VLOG(4) << "Number is a voicemail number.";
251     return PhoneNumberUtil::VOICEMAIL;
252   }
253
254   bool is_fixed_line =
255       IsNumberMatchingDesc(national_number, metadata.fixed_line(),
256                            regexp_cache);
257   if (is_fixed_line) {
258     if (metadata.same_mobile_and_fixed_line_pattern()) {
259       VLOG(4) << "Fixed-line and mobile patterns equal, number is fixed-line"
260               << " or mobile";
261       return PhoneNumberUtil::FIXED_LINE_OR_MOBILE;
262     } else if (IsNumberMatchingDesc(national_number, metadata.mobile(),
263                                     regexp_cache)) {
264       VLOG(4) << "Fixed-line and mobile patterns differ, but number is "
265               << "still fixed-line or mobile";
266       return PhoneNumberUtil::FIXED_LINE_OR_MOBILE;
267     }
268     VLOG(4) << "Number is a fixed line number.";
269     return PhoneNumberUtil::FIXED_LINE;
270   }
271   // Otherwise, test to see if the number is mobile. Only do this if certain
272   // that the patterns for mobile and fixed line aren't the same.
273   if (!metadata.same_mobile_and_fixed_line_pattern() &&
274       IsNumberMatchingDesc(national_number, metadata.mobile(), regexp_cache)) {
275     VLOG(4) << "Number is a mobile number.";
276     return PhoneNumberUtil::MOBILE;
277   }
278   VLOG(4) << "Number type unknown - doesn\'t match any specific number type"
279           << " pattern.";
280   return PhoneNumberUtil::UNKNOWN;
281 }
282
283 char32 ToUnicodeCodepoint(const char* unicode_char) {
284   char32 codepoint;
285   EncodingUtils::DecodeUTF8Char(unicode_char, &codepoint);
286   return codepoint;
287 }
288
289 // Helper initialiser method to create the regular-expression pattern to match
290 // extensions, allowing the one-codepoint extension symbols provided by
291 // single_extn_symbols.
292 // Note that there are currently three capturing groups for the extension itself
293 // - if this number is changed, MaybeStripExtension needs to be updated.
294 string CreateExtnPattern(const string& single_extn_symbols) {
295   static const string capturing_extn_digits = StrCat("([", kDigits, "]{1,7})");
296   // The first regular expression covers RFC 3966 format, where the extension is
297   // added using ";ext=". The second more generic one starts with optional white
298   // space and ends with an optional full stop (.), followed by zero or more
299   // spaces/tabs and then the numbers themselves. The third one covers the
300   // special case of American numbers where the extension is written with a hash
301   // at the end, such as "- 503#".
302   // Note that the only capturing groups should be around the digits that you
303   // want to capture as part of the extension, or else parsing will fail!
304   // Canonical-equivalence doesn't seem to be an option with RE2, so we allow
305   // two options for representing the ó - the character itself, and one in the
306   // unicode decomposed form with the combining acute accent.
307   return (StrCat(
308       kRfc3966ExtnPrefix, capturing_extn_digits, "|"
309        /* "[  \\t,]*(?:e?xt(?:ensi(?:ó?|ó))?n?|e?xtn?|single_extn_symbols|"
310           "int|int|anexo)"
311           "[:\\..]?[  \\t,-]*", capturing_extn_digits, "#?|" */
312       "[ \xC2\xA0\\t,]*(?:e?xt(?:ensi(?:o\xCC\x81?|\xC3\xB3))?n?|"
313       "(?:\xEF\xBD\x85)?\xEF\xBD\x98\xEF\xBD\x94(?:\xEF\xBD\x8E)?|"
314       "[", single_extn_symbols, "]|int|"
315       "\xEF\xBD\x89\xEF\xBD\x8E\xEF\xBD\x94|anexo)"
316       "[:\\.\xEF\xBC\x8E]?[ \xC2\xA0\\t,-]*", capturing_extn_digits,
317       "#?|[- ]+([", kDigits, "]{1,5})#"));
318 }
319
320 // Normalizes a string of characters representing a phone number by replacing
321 // all characters found in the accompanying map with the values therein, and
322 // stripping all other characters if remove_non_matches is true.
323 // Parameters:
324 // number - a pointer to a string of characters representing a phone number to
325 //   be normalized.
326 // normalization_replacements - a mapping of characters to what they should be
327 //   replaced by in the normalized version of the phone number
328 // remove_non_matches - indicates whether characters that are not able to be
329 //   replaced should be stripped from the number. If this is false, they will be
330 //   left unchanged in the number.
331 void NormalizeHelper(const map<char32, char>& normalization_replacements,
332                      bool remove_non_matches,
333                      string* number) {
334   DCHECK(number);
335   UnicodeText number_as_unicode;
336   number_as_unicode.PointToUTF8(number->data(), number->size());
337   string normalized_number;
338   char unicode_char[5];
339   for (UnicodeText::const_iterator it = number_as_unicode.begin();
340        it != number_as_unicode.end();
341        ++it) {
342     map<char32, char>::const_iterator found_glyph_pair =
343         normalization_replacements.find(*it);
344     if (found_glyph_pair != normalization_replacements.end()) {
345       normalized_number.push_back(found_glyph_pair->second);
346     } else if (!remove_non_matches) {
347       // Find out how long this unicode char is so we can append it all.
348       int char_len = it.get_utf8(unicode_char);
349       normalized_number.append(unicode_char, char_len);
350     }
351     // If neither of the above are true, we remove this character.
352   }
353   number->assign(normalized_number);
354 }
355
356 PhoneNumberUtil::ValidationResult TestNumberLengthAgainstPattern(
357     const RegExp& number_pattern, const string& number) {
358   string extracted_number;
359   if (number_pattern.FullMatch(number, &extracted_number)) {
360     return PhoneNumberUtil::IS_POSSIBLE;
361   }
362   if (number_pattern.PartialMatch(number, &extracted_number)) {
363     return PhoneNumberUtil::TOO_LONG;
364   } else {
365     return PhoneNumberUtil::TOO_SHORT;
366   }
367 }
368
369 }  // namespace
370
371 void PhoneNumberUtil::SetLogger(Logger* logger) {
372   logger_.reset(logger);
373   Logger::set_logger_impl(logger_.get());
374 }
375
376 class PhoneNumberRegExpsAndMappings {
377  private:
378   void InitializeMapsAndSets() {
379     diallable_char_mappings_.insert(make_pair('+', '+'));
380     diallable_char_mappings_.insert(make_pair('*', '*'));
381     // Here we insert all punctuation symbols that we wish to respect when
382     // formatting alpha numbers, as they show the intended number groupings.
383     all_plus_number_grouping_symbols_.insert(
384         make_pair(ToUnicodeCodepoint("-"), '-'));
385     all_plus_number_grouping_symbols_.insert(
386         make_pair(ToUnicodeCodepoint("\xEF\xBC\x8D" /* "-" */), '-'));
387     all_plus_number_grouping_symbols_.insert(
388         make_pair(ToUnicodeCodepoint("\xE2\x80\x90" /* "‐" */), '-'));
389     all_plus_number_grouping_symbols_.insert(
390         make_pair(ToUnicodeCodepoint("\xE2\x80\x91" /* "‑" */), '-'));
391     all_plus_number_grouping_symbols_.insert(
392         make_pair(ToUnicodeCodepoint("\xE2\x80\x92" /* "‒" */), '-'));
393     all_plus_number_grouping_symbols_.insert(
394         make_pair(ToUnicodeCodepoint("\xE2\x80\x93" /* "–" */), '-'));
395     all_plus_number_grouping_symbols_.insert(
396         make_pair(ToUnicodeCodepoint("\xE2\x80\x94" /* "—" */), '-'));
397     all_plus_number_grouping_symbols_.insert(
398         make_pair(ToUnicodeCodepoint("\xE2\x80\x95" /* "―" */), '-'));
399     all_plus_number_grouping_symbols_.insert(
400         make_pair(ToUnicodeCodepoint("\xE2\x88\x92" /* "−" */), '-'));
401     all_plus_number_grouping_symbols_.insert(
402         make_pair(ToUnicodeCodepoint("/"), '/'));
403     all_plus_number_grouping_symbols_.insert(
404         make_pair(ToUnicodeCodepoint("\xEF\xBC\x8F" /* "/" */), '/'));
405     all_plus_number_grouping_symbols_.insert(
406         make_pair(ToUnicodeCodepoint(" "), ' '));
407     all_plus_number_grouping_symbols_.insert(
408         make_pair(ToUnicodeCodepoint("\xE3\x80\x80" /* " " */), ' '));
409     all_plus_number_grouping_symbols_.insert(
410         make_pair(ToUnicodeCodepoint("\xE2\x81\xA0"), ' '));
411     all_plus_number_grouping_symbols_.insert(
412         make_pair(ToUnicodeCodepoint("."), '.'));
413     all_plus_number_grouping_symbols_.insert(
414         make_pair(ToUnicodeCodepoint("\xEF\xBC\x8E" /* "." */), '.'));
415     // Only the upper-case letters are added here - the lower-case versions are
416     // added programmatically.
417     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("A"), '2'));
418     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("B"), '2'));
419     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("C"), '2'));
420     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("D"), '3'));
421     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("E"), '3'));
422     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("F"), '3'));
423     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("G"), '4'));
424     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("H"), '4'));
425     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("I"), '4'));
426     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("J"), '5'));
427     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("K"), '5'));
428     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("L"), '5'));
429     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("M"), '6'));
430     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("N"), '6'));
431     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("O"), '6'));
432     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("P"), '7'));
433     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("Q"), '7'));
434     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("R"), '7'));
435     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("S"), '7'));
436     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("T"), '8'));
437     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("U"), '8'));
438     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("V"), '8'));
439     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("W"), '9'));
440     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("X"), '9'));
441     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("Y"), '9'));
442     alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("Z"), '9'));
443     map<char32, char> lower_case_mappings;
444     map<char32, char> alpha_letters;
445     for (map<char32, char>::const_iterator it = alpha_mappings_.begin();
446          it != alpha_mappings_.end();
447          ++it) {
448       // Convert all the upper-case ASCII letters to lower-case.
449       if (it->first < 128) {
450         char letter_as_upper = static_cast<char>(it->first);
451         char32 letter_as_lower = static_cast<char32>(tolower(letter_as_upper));
452         lower_case_mappings.insert(make_pair(letter_as_lower, it->second));
453         // Add the letters in both variants to the alpha_letters map. This just
454         // pairs each letter with its upper-case representation so that it can
455         // be retained when normalising alpha numbers.
456         alpha_letters.insert(make_pair(letter_as_lower, letter_as_upper));
457         alpha_letters.insert(make_pair(it->first, letter_as_upper));
458       }
459     }
460     // In the Java version we don't insert the lower-case mappings in the map,
461     // because we convert to upper case on the fly. Doing this here would
462     // involve pulling in all of ICU, which we don't want to do if we don't have
463     // to.
464     alpha_mappings_.insert(lower_case_mappings.begin(),
465                            lower_case_mappings.end());
466     alpha_phone_mappings_.insert(alpha_mappings_.begin(),
467                                  alpha_mappings_.end());
468     all_plus_number_grouping_symbols_.insert(alpha_letters.begin(),
469                                              alpha_letters.end());
470     // Add the ASCII digits so that they don't get deleted by NormalizeHelper().
471     for (char c = '0'; c <= '9'; ++c) {
472       diallable_char_mappings_.insert(make_pair(c, c));
473       alpha_phone_mappings_.insert(make_pair(c, c));
474       all_plus_number_grouping_symbols_.insert(make_pair(c, c));
475     }
476   }
477
478   // Small string helpers since StrCat has a maximum number of arguments. These
479   // are both used to build valid_phone_number_.
480   const string punctuation_and_star_sign_;
481   const string min_length_phone_number_pattern_;
482
483   // Regular expression of viable phone numbers. This is location independent.
484   // Checks we have at least three leading digits, and only valid punctuation,
485   // alpha characters and digits in the phone number. Does not include extension
486   // data. The symbol 'x' is allowed here as valid punctuation since it is often
487   // used as a placeholder for carrier codes, for example in Brazilian phone
488   // numbers. We also allow multiple plus-signs at the start.
489   // Corresponds to the following:
490   // [digits]{minLengthNsn}|
491   // plus_sign*(([punctuation]|[star])*[digits]){3,}
492   // ([punctuation]|[star]|[digits]|[alpha])*
493   //
494   // The first reg-ex is to allow short numbers (two digits long) to be parsed
495   // if they are entered as "15" etc, but only if there is no punctuation in
496   // them. The second expression restricts the number of digits to three or
497   // more, but then allows them to be in international form, and to have
498   // alpha-characters and punctuation.
499   const string valid_phone_number_;
500
501   // Regexp of all possible ways to write extensions, for use when parsing. This
502   // will be run as a case-insensitive regexp match. Wide character versions are
503   // also provided after each ASCII version.
504   // For parsing, we are slightly more lenient in our interpretation than for
505   // matching. Here we allow a "comma" as a possible extension indicator. When
506   // matching, this is hardly ever used to indicate this.
507   const string extn_patterns_for_parsing_;
508
509  public:
510   scoped_ptr<const AbstractRegExpFactory> regexp_factory_;
511   scoped_ptr<RegExpCache> regexp_cache_;
512
513   // A map that contains characters that are essential when dialling. That means
514   // any of the characters in this map must not be removed from a number when
515   // dialing, otherwise the call will not reach the intended destination.
516   map<char32, char> diallable_char_mappings_;
517   // These mappings map a character (key) to a specific digit that should
518   // replace it for normalization purposes.
519   map<char32, char> alpha_mappings_;
520   // For performance reasons, store a map of combining alpha_mappings with ASCII
521   // digits.
522   map<char32, char> alpha_phone_mappings_;
523
524   // Separate map of all symbols that we wish to retain when formatting alpha
525   // numbers. This includes digits, ascii letters and number grouping symbols
526   // such as "-" and " ".
527   map<char32, char> all_plus_number_grouping_symbols_;
528
529   // Pattern that makes it easy to distinguish whether a region has a unique
530   // international dialing prefix or not. If a region has a unique international
531   // prefix (e.g. 011 in USA), it will be represented as a string that contains
532   // a sequence of ASCII digits. If there are multiple available international
533   // prefixes in a region, they will be represented as a regex string that
534   // always contains character(s) other than ASCII digits.
535   // Note this regex also includes tilde, which signals waiting for the tone.
536   scoped_ptr<const RegExp> unique_international_prefix_;
537
538   scoped_ptr<const RegExp> digits_pattern_;
539   scoped_ptr<const RegExp> capturing_digit_pattern_;
540   scoped_ptr<const RegExp> capturing_ascii_digits_pattern_;
541
542   // Regular expression of acceptable characters that may start a phone number
543   // for the purposes of parsing. This allows us to strip away meaningless
544   // prefixes to phone numbers that may be mistakenly given to us. This consists
545   // of digits, the plus symbol and arabic-indic digits. This does not contain
546   // alpha characters, although they may be used later in the number. It also
547   // does not include other punctuation, as this will be stripped later during
548   // parsing and is of no information value when parsing a number. The string
549   // starting with this valid character is captured.
550   // This corresponds to VALID_START_CHAR in the java version.
551   scoped_ptr<const RegExp> valid_start_char_pattern_;
552
553   // Regular expression of valid characters before a marker that might indicate
554   // a second number.
555   scoped_ptr<const RegExp> capture_up_to_second_number_start_pattern_;
556
557   // Regular expression of trailing characters that we want to remove. We remove
558   // all characters that are not alpha or numerical characters. The hash
559   // character is retained here, as it may signify the previous block was an
560   // extension. Note the capturing block at the start to capture the rest of the
561   // number if this was a match.
562   // This corresponds to UNWANTED_END_CHAR_PATTERN in the java version.
563   scoped_ptr<const RegExp> unwanted_end_char_pattern_;
564
565   // Regular expression of groups of valid punctuation characters.
566   scoped_ptr<const RegExp> separator_pattern_;
567
568   // Regexp of all possible ways to write extensions, for use when finding phone
569   // numbers in text. This will be run as a case-insensitive regexp match. Wide
570   // character versions are also provided after each ASCII version.
571   const string extn_patterns_for_matching_;
572
573   // Regexp of all known extension prefixes used by different regions followed
574   // by 1 or more valid digits, for use when parsing.
575   scoped_ptr<const RegExp> extn_pattern_;
576
577   // We append optionally the extension pattern to the end here, as a valid
578   // phone number may have an extension prefix appended, followed by 1 or more
579   // digits.
580   scoped_ptr<const RegExp> valid_phone_number_pattern_;
581
582   // We use this pattern to check if the phone number has at least three letters
583   // in it - if so, then we treat it as a number where some phone-number digits
584   // are represented by letters.
585   scoped_ptr<const RegExp> valid_alpha_phone_pattern_;
586
587   scoped_ptr<const RegExp> first_group_capturing_pattern_;
588
589   scoped_ptr<const RegExp> carrier_code_pattern_;
590
591   scoped_ptr<const RegExp> plus_chars_pattern_;
592
593   PhoneNumberRegExpsAndMappings()
594       : punctuation_and_star_sign_(StrCat(PhoneNumberUtil::kValidPunctuation,
595                                           kStarSign)),
596         min_length_phone_number_pattern_(
597             StrCat(kDigits, "{", PhoneNumberUtil::kMinLengthForNsn, "}")),
598         valid_phone_number_(
599             StrCat(min_length_phone_number_pattern_, "|[",
600                    PhoneNumberUtil::kPlusChars, "]*(?:[",
601                    punctuation_and_star_sign_, "]*",
602                    kDigits, "){3,}[", kValidAlpha,
603                    punctuation_and_star_sign_, kDigits,
604                    "]*")),
605         extn_patterns_for_parsing_(
606             CreateExtnPattern(StrCat(",", kSingleExtnSymbolsForMatching))),
607         regexp_factory_(new RegExpFactory()),
608         regexp_cache_(new RegExpCache(*regexp_factory_.get(), 128)),
609         diallable_char_mappings_(),
610         alpha_mappings_(),
611         alpha_phone_mappings_(),
612         all_plus_number_grouping_symbols_(),
613         unique_international_prefix_(regexp_factory_->CreateRegExp(
614             /* "[\\d]+(?:[~⁓∼~][\\d]+)?" */
615             "[\\d]+(?:[~\xE2\x81\x93\xE2\x88\xBC\xEF\xBD\x9E][\\d]+)?")),
616         digits_pattern_(
617             regexp_factory_->CreateRegExp(StrCat("[", kDigits, "]*"))),
618         capturing_digit_pattern_(
619             regexp_factory_->CreateRegExp(StrCat("([", kDigits, "])"))),
620         capturing_ascii_digits_pattern_(
621             regexp_factory_->CreateRegExp("(\\d+)")),
622         valid_start_char_pattern_(regexp_factory_->CreateRegExp(
623             StrCat("[", PhoneNumberUtil::kPlusChars, kDigits, "]"))),
624         capture_up_to_second_number_start_pattern_(
625             regexp_factory_->CreateRegExp(
626                 PhoneNumberUtil::kCaptureUpToSecondNumberStart)),
627         unwanted_end_char_pattern_(
628             regexp_factory_->CreateRegExp("[^\\p{N}\\p{L}#]")),
629         separator_pattern_(
630             regexp_factory_->CreateRegExp(
631                 StrCat("[", PhoneNumberUtil::kValidPunctuation, "]+"))),
632         extn_patterns_for_matching_(
633             CreateExtnPattern(kSingleExtnSymbolsForMatching)),
634         extn_pattern_(regexp_factory_->CreateRegExp(
635             StrCat("(?i)(?:", extn_patterns_for_parsing_, ")$"))),
636         valid_phone_number_pattern_(regexp_factory_->CreateRegExp(
637             StrCat("(?i)", valid_phone_number_,
638                    "(?:", extn_patterns_for_parsing_, ")?"))),
639         valid_alpha_phone_pattern_(regexp_factory_->CreateRegExp(
640             StrCat("(?i)(?:.*?[", kValidAlpha, "]){3}"))),
641         // The first_group_capturing_pattern was originally set to $1 but there
642         // are some countries for which the first group is not used in the
643         // national pattern (e.g. Argentina) so the $1 group does not match
644         // correctly. Therefore, we use \d, so that the first group actually
645         // used in the pattern will be matched.
646         first_group_capturing_pattern_(
647             regexp_factory_->CreateRegExp("(\\$\\d)")),
648         carrier_code_pattern_(regexp_factory_->CreateRegExp("\\$CC")),
649         plus_chars_pattern_(
650             regexp_factory_->CreateRegExp(
651                 StrCat("[", PhoneNumberUtil::kPlusChars, "]+"))) {
652     InitializeMapsAndSets();
653   }
654
655  private:
656   DISALLOW_COPY_AND_ASSIGN(PhoneNumberRegExpsAndMappings);
657 };
658
659 // Private constructor. Also takes care of initialisation.
660 PhoneNumberUtil::PhoneNumberUtil()
661     : logger_(Logger::set_logger_impl(new NullLogger())),
662       reg_exps_(new PhoneNumberRegExpsAndMappings),
663       country_calling_code_to_region_code_map_(new vector<IntRegionsPair>()),
664       nanpa_regions_(new set<string>()),
665       region_to_metadata_map_(new map<string, PhoneMetadata>()),
666       country_code_to_non_geographical_metadata_map_(
667           new map<int, PhoneMetadata>) {
668   Logger::set_logger_impl(logger_.get());
669   // TODO: Update the java version to put the contents of the init
670   // method inside the constructor as well to keep both in sync.
671   PhoneMetadataCollection metadata_collection;
672   if (!LoadCompiledInMetadata(&metadata_collection)) {
673     LOG(DFATAL) << "Could not parse compiled-in metadata.";
674     return;
675   }
676   // Storing data in a temporary map to make it easier to find other regions
677   // that share a country calling code when inserting data.
678   map<int, list<string>* > country_calling_code_to_region_map;
679   for (RepeatedPtrField<PhoneMetadata>::const_iterator it =
680            metadata_collection.metadata().begin();
681        it != metadata_collection.metadata().end();
682        ++it) {
683     const string& region_code = it->id();
684     if (region_code == RegionCode::GetUnknown()) {
685       continue;
686     }
687
688     int country_calling_code = it->country_code();
689     if (kRegionCodeForNonGeoEntity == region_code) {
690       country_code_to_non_geographical_metadata_map_->insert(
691           make_pair(country_calling_code, *it));
692     } else {
693       region_to_metadata_map_->insert(make_pair(region_code, *it));
694     }
695     map<int, list<string>* >::iterator calling_code_in_map =
696         country_calling_code_to_region_map.find(country_calling_code);
697     if (calling_code_in_map != country_calling_code_to_region_map.end()) {
698       if (it->main_country_for_code()) {
699         calling_code_in_map->second->push_front(region_code);
700       } else {
701         calling_code_in_map->second->push_back(region_code);
702       }
703     } else {
704       // For most country calling codes, there will be only one region code.
705       list<string>* list_with_region_code = new list<string>();
706       list_with_region_code->push_back(region_code);
707       country_calling_code_to_region_map.insert(
708           make_pair(country_calling_code, list_with_region_code));
709     }
710     if (country_calling_code == kNanpaCountryCode) {
711         nanpa_regions_->insert(region_code);
712     }
713   }
714
715   country_calling_code_to_region_code_map_->insert(
716       country_calling_code_to_region_code_map_->begin(),
717       country_calling_code_to_region_map.begin(),
718       country_calling_code_to_region_map.end());
719   // Sort all the pairs in ascending order according to country calling code.
720   sort(country_calling_code_to_region_code_map_->begin(),
721        country_calling_code_to_region_code_map_->end(),
722        OrderByFirst());
723 }
724
725 PhoneNumberUtil::~PhoneNumberUtil() {
726   STLDeleteContainerPairSecondPointers(
727       country_calling_code_to_region_code_map_->begin(),
728       country_calling_code_to_region_code_map_->end());
729 }
730
731 void PhoneNumberUtil::GetSupportedRegions(set<string>* regions) const {
732   DCHECK(regions);
733   for (map<string, PhoneMetadata>::const_iterator it =
734        region_to_metadata_map_->begin(); it != region_to_metadata_map_->end();
735        ++it) {
736     regions->insert(it->first);
737   }
738 }
739
740 // Public wrapper function to get a PhoneNumberUtil instance with the default
741 // metadata file.
742 // static
743 PhoneNumberUtil* PhoneNumberUtil::GetInstance() {
744   return Singleton<PhoneNumberUtil>::GetInstance();
745 }
746
747 const string& PhoneNumberUtil::GetExtnPatternsForMatching() const {
748   return reg_exps_->extn_patterns_for_matching_;
749 }
750
751 bool PhoneNumberUtil::StartsWithPlusCharsPattern(const string& number)
752     const {
753   const scoped_ptr<RegExpInput> number_string_piece(
754       reg_exps_->regexp_factory_->CreateInput(number));
755   return reg_exps_->plus_chars_pattern_->Consume(number_string_piece.get());
756 }
757
758 bool PhoneNumberUtil::ContainsOnlyValidDigits(const string& s) const {
759   return reg_exps_->digits_pattern_->FullMatch(s);
760 }
761
762 void PhoneNumberUtil::TrimUnwantedEndChars(string* number) const {
763   DCHECK(number);
764   UnicodeText number_as_unicode;
765   number_as_unicode.PointToUTF8(number->data(), number->size());
766   char current_char[5];
767   int len;
768   UnicodeText::const_reverse_iterator reverse_it(number_as_unicode.end());
769   for (; reverse_it.base() != number_as_unicode.begin(); ++reverse_it) {
770     len = reverse_it.get_utf8(current_char);
771     current_char[len] = '\0';
772     if (!reg_exps_->unwanted_end_char_pattern_->FullMatch(current_char)) {
773       break;
774     }
775   }
776
777   number->assign(UnicodeText::UTF8Substring(number_as_unicode.begin(),
778                                             reverse_it.base()));
779 }
780
781 bool PhoneNumberUtil::IsFormatEligibleForAsYouTypeFormatter(
782     const string& format) const {
783   // A pattern that is used to determine if a numberFormat under
784   // availableFormats is eligible to be used by the AYTF. It is eligible when
785   // the format element under numberFormat contains groups of the dollar sign
786   // followed by a single digit, separated by valid phone number punctuation.
787   // This prevents invalid punctuation (such as the star sign in Israeli star
788   // numbers) getting into the output of the AYTF.
789   const RegExp& eligible_format_pattern = reg_exps_->regexp_cache_->GetRegExp(
790       StrCat("[", kValidPunctuation, "]*", "(\\$\\d", "[",
791              kValidPunctuation, "]*)+"));
792   return eligible_format_pattern.FullMatch(format);
793 }
794
795 bool PhoneNumberUtil::FormattingRuleHasFirstGroupOnly(
796     const string& national_prefix_formatting_rule) const {
797   // A pattern that is used to determine if the national prefix formatting rule
798   // has the first group only, i.e., does not start with the national prefix.
799   // Note that the pattern explicitly allows for unbalanced parentheses.
800   const RegExp& first_group_only_prefix_pattern =
801       reg_exps_->regexp_cache_->GetRegExp("\\(?\\$1\\)?");
802   return first_group_only_prefix_pattern.FullMatch(
803       national_prefix_formatting_rule);
804 }
805
806 void PhoneNumberUtil::GetNddPrefixForRegion(const string& region_code,
807                                             bool strip_non_digits,
808                                             string* national_prefix) const {
809   DCHECK(national_prefix);
810   const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
811   if (!metadata) {
812     LOG(WARNING) << "Invalid or unknown region code (" << region_code
813                  << ") provided.";
814     return;
815   }
816   national_prefix->assign(metadata->national_prefix());
817   if (strip_non_digits) {
818     // Note: if any other non-numeric symbols are ever used in national
819     // prefixes, these would have to be removed here as well.
820     strrmm(national_prefix, "~");
821   }
822 }
823
824 bool PhoneNumberUtil::IsValidRegionCode(const string& region_code) const {
825   return (region_to_metadata_map_->find(region_code) !=
826           region_to_metadata_map_->end());
827 }
828
829 bool PhoneNumberUtil::HasValidCountryCallingCode(
830     int country_calling_code) const {
831   // Create an IntRegionsPair with the country_code passed in, and use it to
832   // locate the pair with the same country_code in the sorted vector.
833   IntRegionsPair target_pair;
834   target_pair.first = country_calling_code;
835   return (binary_search(country_calling_code_to_region_code_map_->begin(),
836                         country_calling_code_to_region_code_map_->end(),
837                         target_pair, OrderByFirst()));
838 }
839
840 // Returns a pointer to the phone metadata for the appropriate region or NULL
841 // if the region code is invalid or unknown.
842 const PhoneMetadata* PhoneNumberUtil::GetMetadataForRegion(
843     const string& region_code) const {
844   map<string, PhoneMetadata>::const_iterator it =
845       region_to_metadata_map_->find(region_code);
846   if (it != region_to_metadata_map_->end()) {
847     return &it->second;
848   }
849   return NULL;
850 }
851
852 const PhoneMetadata* PhoneNumberUtil::GetMetadataForNonGeographicalRegion(
853     int country_calling_code) const {
854   map<int, PhoneMetadata>::const_iterator it =
855       country_code_to_non_geographical_metadata_map_->find(
856           country_calling_code);
857   if (it != country_code_to_non_geographical_metadata_map_->end()) {
858     return &it->second;
859   }
860   return NULL;
861 }
862
863 void PhoneNumberUtil::Format(const PhoneNumber& number,
864                              PhoneNumberFormat number_format,
865                              string* formatted_number) const {
866   DCHECK(formatted_number);
867   if (number.national_number() == 0) {
868     const string& raw_input = number.raw_input();
869     if (!raw_input.empty()) {
870       // Unparseable numbers that kept their raw input just use that.
871       // This is the only case where a number can be formatted as E164 without a
872       // leading '+' symbol (but the original number wasn't parseable anyway).
873       // TODO: Consider removing the 'if' above so that unparseable
874       // strings without raw input format to the empty string instead of "+00".
875       formatted_number->assign(raw_input);
876       return;
877     }
878   }
879   int country_calling_code = number.country_code();
880   string national_significant_number;
881   GetNationalSignificantNumber(number, &national_significant_number);
882   if (number_format == E164) {
883     // Early exit for E164 case (even if the country calling code is invalid)
884     // since no formatting of the national number needs to be applied.
885     // Extensions are not formatted.
886     formatted_number->assign(national_significant_number);
887     PrefixNumberWithCountryCallingCode(country_calling_code, E164,
888                                        formatted_number);
889     return;
890   }
891   if (!HasValidCountryCallingCode(country_calling_code)) {
892     formatted_number->assign(national_significant_number);
893     return;
894   }
895   // Note here that all NANPA formatting rules are contained by US, so we use
896   // that to format NANPA numbers. The same applies to Russian Fed regions -
897   // rules are contained by Russia. French Indian Ocean country rules are
898   // contained by Réunion.
899   string region_code;
900   GetRegionCodeForCountryCode(country_calling_code, &region_code);
901   // Metadata cannot be NULL because the country calling code is valid (which
902   // means that the region code cannot be ZZ and must be one of our supported
903   // region codes).
904   const PhoneMetadata* metadata =
905       GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
906   FormatNsn(national_significant_number, *metadata, number_format,
907             formatted_number);
908   MaybeAppendFormattedExtension(number, *metadata, number_format,
909                                 formatted_number);
910   PrefixNumberWithCountryCallingCode(country_calling_code, number_format,
911                                      formatted_number);
912 }
913
914 void PhoneNumberUtil::FormatByPattern(
915     const PhoneNumber& number,
916     PhoneNumberFormat number_format,
917     const RepeatedPtrField<NumberFormat>& user_defined_formats,
918     string* formatted_number) const {
919   DCHECK(formatted_number);
920   int country_calling_code = number.country_code();
921   // Note GetRegionCodeForCountryCode() is used because formatting information
922   // for regions which share a country calling code is contained by only one
923   // region for performance reasons. For example, for NANPA regions it will be
924   // contained in the metadata for US.
925   string national_significant_number;
926   GetNationalSignificantNumber(number, &national_significant_number);
927   if (!HasValidCountryCallingCode(country_calling_code)) {
928     formatted_number->assign(national_significant_number);
929     return;
930   }
931   string region_code;
932   GetRegionCodeForCountryCode(country_calling_code, &region_code);
933   // Metadata cannot be NULL because the country calling code is valid.
934   const PhoneMetadata* metadata =
935       GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
936   const NumberFormat* formatting_pattern =
937       ChooseFormattingPatternForNumber(user_defined_formats,
938                                        national_significant_number);
939   if (!formatting_pattern) {
940     // If no pattern above is matched, we format the number as a whole.
941     formatted_number->assign(national_significant_number);
942   } else {
943     NumberFormat num_format_copy;
944     // Before we do a replacement of the national prefix pattern $NP with the
945     // national prefix, we need to copy the rule so that subsequent replacements
946     // for different numbers have the appropriate national prefix.
947     num_format_copy.MergeFrom(*formatting_pattern);
948     string national_prefix_formatting_rule(
949         formatting_pattern->national_prefix_formatting_rule());
950     if (!national_prefix_formatting_rule.empty()) {
951       const string& national_prefix = metadata->national_prefix();
952       if (!national_prefix.empty()) {
953         // Replace $NP with national prefix and $FG with the first group ($1).
954         GlobalReplaceSubstring("$NP", national_prefix,
955                                &national_prefix_formatting_rule);
956         GlobalReplaceSubstring("$FG", "$1",
957                                &national_prefix_formatting_rule);
958         num_format_copy.set_national_prefix_formatting_rule(
959             national_prefix_formatting_rule);
960       } else {
961         // We don't want to have a rule for how to format the national prefix if
962         // there isn't one.
963         num_format_copy.clear_national_prefix_formatting_rule();
964       }
965     }
966     FormatNsnUsingPattern(national_significant_number, num_format_copy,
967                           number_format, formatted_number);
968   }
969   MaybeAppendFormattedExtension(number, *metadata, NATIONAL, formatted_number);
970   PrefixNumberWithCountryCallingCode(country_calling_code, number_format,
971                                      formatted_number);
972 }
973
974 void PhoneNumberUtil::FormatNationalNumberWithCarrierCode(
975     const PhoneNumber& number,
976     const string& carrier_code,
977     string* formatted_number) const {
978   int country_calling_code = number.country_code();
979   string national_significant_number;
980   GetNationalSignificantNumber(number, &national_significant_number);
981   if (!HasValidCountryCallingCode(country_calling_code)) {
982     formatted_number->assign(national_significant_number);
983     return;
984   }
985
986   // Note GetRegionCodeForCountryCode() is used because formatting information
987   // for regions which share a country calling code is contained by only one
988   // region for performance reasons. For example, for NANPA regions it will be
989   // contained in the metadata for US.
990   string region_code;
991   GetRegionCodeForCountryCode(country_calling_code, &region_code);
992   // Metadata cannot be NULL because the country calling code is valid.
993   const PhoneMetadata* metadata =
994       GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
995   FormatNsnWithCarrier(national_significant_number, *metadata, NATIONAL,
996                        carrier_code, formatted_number);
997   MaybeAppendFormattedExtension(number, *metadata, NATIONAL, formatted_number);
998   PrefixNumberWithCountryCallingCode(country_calling_code, NATIONAL,
999                                      formatted_number);
1000 }
1001
1002 const PhoneMetadata* PhoneNumberUtil::GetMetadataForRegionOrCallingCode(
1003       int country_calling_code, const string& region_code) const {
1004   return kRegionCodeForNonGeoEntity == region_code
1005       ? GetMetadataForNonGeographicalRegion(country_calling_code)
1006       : GetMetadataForRegion(region_code);
1007 }
1008
1009 void PhoneNumberUtil::FormatNationalNumberWithPreferredCarrierCode(
1010     const PhoneNumber& number,
1011     const string& fallback_carrier_code,
1012     string* formatted_number) const {
1013   FormatNationalNumberWithCarrierCode(
1014       number,
1015       number.has_preferred_domestic_carrier_code()
1016           ? number.preferred_domestic_carrier_code()
1017           : fallback_carrier_code,
1018       formatted_number);
1019 }
1020
1021 void PhoneNumberUtil::FormatNumberForMobileDialing(
1022     const PhoneNumber& number,
1023     const string& calling_from,
1024     bool with_formatting,
1025     string* formatted_number) const {
1026   int country_calling_code = number.country_code();
1027   if (!HasValidCountryCallingCode(country_calling_code)) {
1028     formatted_number->assign(number.has_raw_input() ? number.raw_input() : "");
1029     return;
1030   }
1031
1032   formatted_number->assign("");
1033   // Clear the extension, as that part cannot normally be dialed together with
1034   // the main number.
1035   PhoneNumber number_no_extension(number);
1036   number_no_extension.clear_extension();
1037   string region_code;
1038   GetRegionCodeForCountryCode(country_calling_code, &region_code);
1039   if (calling_from == region_code) {
1040     PhoneNumberType number_type = GetNumberType(number_no_extension);
1041     bool is_fixed_line_or_mobile =
1042         (number_type == FIXED_LINE) || (number_type == MOBILE) ||
1043         (number_type == FIXED_LINE_OR_MOBILE);
1044     // Carrier codes may be needed in some countries. We handle this here.
1045     if ((region_code == "CO") && (number_type == FIXED_LINE)) {
1046       FormatNationalNumberWithCarrierCode(
1047           number_no_extension, kColombiaMobileToFixedLinePrefix,
1048           formatted_number);
1049     } else if ((region_code == "BR") && (is_fixed_line_or_mobile)) {
1050       if (number_no_extension.has_preferred_domestic_carrier_code()) {
1051       FormatNationalNumberWithPreferredCarrierCode(number_no_extension, "",
1052                                                    formatted_number);
1053       } else {
1054         // Brazilian fixed line and mobile numbers need to be dialed with a
1055         // carrier code when called within Brazil. Without that, most of the
1056         // carriers won't connect the call. Because of that, we return an empty
1057         // string here.
1058         formatted_number->assign("");
1059       }
1060     } else {
1061       // For NANPA countries, non-geographical countries, and Mexican fixed line
1062       // and mobile numbers, we output international format for numbers that can
1063       // be dialed internationally as that always works.
1064       if ((country_calling_code == kNanpaCountryCode ||
1065            region_code == kRegionCodeForNonGeoEntity ||
1066            // MX fixed line and mobile numbers should always be formatted in
1067            // international format, even when dialed within MX. For national
1068            // format to work, a carrier code needs to be used, and the correct
1069            // carrier code depends on if the caller and callee are from the same
1070            // local area. It is trickier to get that to work correctly than
1071            // using international format, which is tested to work fine on all
1072            // carriers.
1073            (region_code == "MX" && is_fixed_line_or_mobile)) &&
1074           CanBeInternationallyDialled(number_no_extension)) {
1075         Format(number_no_extension, INTERNATIONAL, formatted_number);
1076       } else {
1077         Format(number_no_extension, NATIONAL, formatted_number);
1078       }
1079
1080     }
1081   } else if (CanBeInternationallyDialled(number_no_extension)) {
1082     with_formatting
1083         ? Format(number_no_extension, INTERNATIONAL, formatted_number)
1084         : Format(number_no_extension, E164, formatted_number);
1085     return;
1086   }
1087   if (!with_formatting) {
1088     NormalizeHelper(reg_exps_->diallable_char_mappings_,
1089                     true /* remove non matches */, formatted_number);
1090   }
1091 }
1092
1093 void PhoneNumberUtil::FormatOutOfCountryCallingNumber(
1094     const PhoneNumber& number,
1095     const string& calling_from,
1096     string* formatted_number) const {
1097   DCHECK(formatted_number);
1098   if (!IsValidRegionCode(calling_from)) {
1099     LOG(WARNING) << "Trying to format number from invalid region "
1100                  << calling_from
1101                  << ". International formatting applied.";
1102     Format(number, INTERNATIONAL, formatted_number);
1103     return;
1104   }
1105   int country_code = number.country_code();
1106   string national_significant_number;
1107   GetNationalSignificantNumber(number, &national_significant_number);
1108   if (!HasValidCountryCallingCode(country_code)) {
1109     formatted_number->assign(national_significant_number);
1110     return;
1111   }
1112   if (country_code == kNanpaCountryCode) {
1113     if (IsNANPACountry(calling_from)) {
1114       // For NANPA regions, return the national format for these regions but
1115       // prefix it with the country calling code.
1116       Format(number, NATIONAL, formatted_number);
1117       formatted_number->insert(0, StrCat(country_code, " "));
1118       return;
1119     }
1120   } else if (country_code == GetCountryCodeForValidRegion(calling_from)) {
1121     // If neither region is a NANPA region, then we check to see if the
1122     // country calling code of the number and the country calling code of the
1123     // region we are calling from are the same.
1124     // For regions that share a country calling code, the country calling code
1125     // need not be dialled. This also applies when dialling within a region, so
1126     // this if clause covers both these cases.
1127     // Technically this is the case for dialling from la Réunion to other
1128     // overseas departments of France (French Guiana, Martinique, Guadeloupe),
1129     // but not vice versa - so we don't cover this edge case for now and for
1130     // those cases return the version including country calling code.
1131     // Details here:
1132     // http://www.petitfute.com/voyage/225-info-pratiques-reunion
1133     Format(number, NATIONAL, formatted_number);
1134     return;
1135   }
1136   // Metadata cannot be NULL because we checked 'IsValidRegionCode()' above.
1137   const PhoneMetadata* metadata_calling_from =
1138       GetMetadataForRegion(calling_from);
1139   const string& international_prefix =
1140       metadata_calling_from->international_prefix();
1141
1142   // For regions that have multiple international prefixes, the international
1143   // format of the number is returned, unless there is a preferred international
1144   // prefix.
1145   const string international_prefix_for_formatting(
1146       reg_exps_->unique_international_prefix_->FullMatch(international_prefix)
1147       ? international_prefix
1148       : metadata_calling_from->preferred_international_prefix());
1149
1150   string region_code;
1151   GetRegionCodeForCountryCode(country_code, &region_code);
1152   // Metadata cannot be NULL because the country_code is valid.
1153   const PhoneMetadata* metadata_for_region =
1154       GetMetadataForRegionOrCallingCode(country_code, region_code);
1155   FormatNsn(national_significant_number, *metadata_for_region, INTERNATIONAL,
1156             formatted_number);
1157   MaybeAppendFormattedExtension(number, *metadata_for_region, INTERNATIONAL,
1158                                 formatted_number);
1159   if (!international_prefix_for_formatting.empty()) {
1160     formatted_number->insert(
1161         0, StrCat(international_prefix_for_formatting, " ", country_code, " "));
1162   } else {
1163     PrefixNumberWithCountryCallingCode(country_code, INTERNATIONAL,
1164                                        formatted_number);
1165   }
1166 }
1167
1168 void PhoneNumberUtil::FormatInOriginalFormat(const PhoneNumber& number,
1169                                              const string& region_calling_from,
1170                                              string* formatted_number) const {
1171   DCHECK(formatted_number);
1172
1173   if (number.has_raw_input() &&
1174       (HasUnexpectedItalianLeadingZero(number) ||
1175        !HasFormattingPatternForNumber(number))) {
1176     // We check if we have the formatting pattern because without that, we might
1177     // format the number as a group without national prefix.
1178     formatted_number->assign(number.raw_input());
1179     return;
1180   }
1181   if (!number.has_country_code_source()) {
1182     Format(number, NATIONAL, formatted_number);
1183     return;
1184   }
1185   switch (number.country_code_source()) {
1186     case PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN:
1187       Format(number, INTERNATIONAL, formatted_number);
1188       break;
1189     case PhoneNumber::FROM_NUMBER_WITH_IDD:
1190       FormatOutOfCountryCallingNumber(number, region_calling_from,
1191                                       formatted_number);
1192       break;
1193     case PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN:
1194       Format(number, INTERNATIONAL, formatted_number);
1195       formatted_number->erase(formatted_number->begin());
1196       break;
1197     case PhoneNumber::FROM_DEFAULT_COUNTRY:
1198       // Fall-through to default case.
1199     default:
1200       string region_code;
1201       GetRegionCodeForCountryCode(number.country_code(), &region_code);
1202       // We strip non-digits from the NDD here, and from the raw input later, so
1203       // that we can compare them easily.
1204       string national_prefix;
1205       GetNddPrefixForRegion(region_code, true /* strip non-digits */,
1206                             &national_prefix);
1207       if (national_prefix.empty()) {
1208         // If the region doesn't have a national prefix at all, we can safely
1209         // return the national format without worrying about a national prefix
1210         // being added.
1211         Format(number, NATIONAL, formatted_number);
1212         break;
1213       }
1214       // Otherwise, we check if the original number was entered with a national
1215       // prefix.
1216       if (RawInputContainsNationalPrefix(number.raw_input(), national_prefix,
1217                                          region_code)) {
1218         // If so, we can safely return the national format.
1219         Format(number, NATIONAL, formatted_number);
1220         break;
1221       }
1222       // Metadata cannot be NULL here because GetNddPrefixForRegion() (above)
1223       // leaves the prefix empty if there is no metadata for the region.
1224       const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
1225       string national_number;
1226       GetNationalSignificantNumber(number, &national_number);
1227       // This shouldn't be NULL, because we have checked that above with
1228       // HasFormattingPatternForNumber.
1229       const NumberFormat* format_rule =
1230           ChooseFormattingPatternForNumber(metadata->number_format(),
1231                                            national_number);
1232       // The format rule could still be NULL here if the national number was 0
1233       // and there was no raw input (this should not be possible for numbers
1234       // generated by the phonenumber library as they would also not have a
1235       // country calling code and we would have exited earlier).
1236       if (!format_rule) {
1237         Format(number, NATIONAL, formatted_number);
1238         break;
1239       }
1240       // When the format we apply to this number doesn't contain national
1241       // prefix, we can just return the national format.
1242       // TODO: Refactor the code below with the code in
1243       // IsNationalPrefixPresentIfRequired.
1244       string candidate_national_prefix_rule(
1245           format_rule->national_prefix_formatting_rule());
1246       // We assume that the first-group symbol will never be _before_ the
1247       // national prefix.
1248       if (!candidate_national_prefix_rule.empty()) {
1249         candidate_national_prefix_rule.erase(
1250             candidate_national_prefix_rule.find("$1"));
1251         NormalizeDigitsOnly(&candidate_national_prefix_rule);
1252       }
1253       if (candidate_national_prefix_rule.empty()) {
1254         // National prefix not used when formatting this number.
1255         Format(number, NATIONAL, formatted_number);
1256         break;
1257       }
1258       // Otherwise, we need to remove the national prefix from our output.
1259       RepeatedPtrField<NumberFormat> number_formats;
1260       NumberFormat* number_format = number_formats.Add();
1261       number_format->MergeFrom(*format_rule);
1262       number_format->clear_national_prefix_formatting_rule();
1263       FormatByPattern(number, NATIONAL, number_formats, formatted_number);
1264       break;
1265   }
1266   // If no digit is inserted/removed/modified as a result of our formatting, we
1267   // return the formatted phone number; otherwise we return the raw input the
1268   // user entered.
1269   if (!formatted_number->empty() && !number.raw_input().empty()) {
1270     string normalized_formatted_number(*formatted_number);
1271     NormalizeHelper(reg_exps_->diallable_char_mappings_,
1272                     true /* remove non matches */,
1273                     &normalized_formatted_number);
1274     string normalized_raw_input(number.raw_input());
1275     NormalizeHelper(reg_exps_->diallable_char_mappings_,
1276                     true /* remove non matches */, &normalized_raw_input);
1277     if (normalized_formatted_number != normalized_raw_input) {
1278       formatted_number->assign(number.raw_input());
1279     }
1280   }
1281 }
1282
1283 // Check if raw_input, which is assumed to be in the national format, has a
1284 // national prefix. The national prefix is assumed to be in digits-only form.
1285 bool PhoneNumberUtil::RawInputContainsNationalPrefix(
1286     const string& raw_input,
1287     const string& national_prefix,
1288     const string& region_code) const {
1289   string normalized_national_number(raw_input);
1290   NormalizeDigitsOnly(&normalized_national_number);
1291   if (HasPrefixString(normalized_national_number, national_prefix)) {
1292     // Some Japanese numbers (e.g. 00777123) might be mistaken to contain
1293     // the national prefix when written without it (e.g. 0777123) if we just
1294     // do prefix matching. To tackle that, we check the validity of the
1295     // number if the assumed national prefix is removed (777123 won't be
1296     // valid in Japan).
1297     PhoneNumber number_without_national_prefix;
1298     if (Parse(normalized_national_number.substr(national_prefix.length()),
1299               region_code, &number_without_national_prefix)
1300         == NO_PARSING_ERROR) {
1301       return IsValidNumber(number_without_national_prefix);
1302     }
1303   }
1304   return false;
1305 }
1306
1307 bool PhoneNumberUtil::HasUnexpectedItalianLeadingZero(
1308     const PhoneNumber& number) const {
1309   return number.has_italian_leading_zero() &&
1310       !IsLeadingZeroPossible(number.country_code());
1311 }
1312
1313 bool PhoneNumberUtil::HasFormattingPatternForNumber(
1314     const PhoneNumber& number) const {
1315   int country_calling_code = number.country_code();
1316   string region_code;
1317   GetRegionCodeForCountryCode(country_calling_code, &region_code);
1318   const PhoneMetadata* metadata =
1319       GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
1320   if (!metadata) {
1321     return false;
1322   }
1323   string national_number;
1324   GetNationalSignificantNumber(number, &national_number);
1325   const NumberFormat* format_rule =
1326       ChooseFormattingPatternForNumber(metadata->number_format(),
1327                                        national_number);
1328   return format_rule;
1329 }
1330
1331 void PhoneNumberUtil::FormatOutOfCountryKeepingAlphaChars(
1332     const PhoneNumber& number,
1333     const string& calling_from,
1334     string* formatted_number) const {
1335   // If there is no raw input, then we can't keep alpha characters because there
1336   // aren't any. In this case, we return FormatOutOfCountryCallingNumber.
1337   if (number.raw_input().empty()) {
1338     FormatOutOfCountryCallingNumber(number, calling_from, formatted_number);
1339     return;
1340   }
1341   int country_code = number.country_code();
1342   if (!HasValidCountryCallingCode(country_code)) {
1343     formatted_number->assign(number.raw_input());
1344     return;
1345   }
1346   // Strip any prefix such as country calling code, IDD, that was present. We do
1347   // this by comparing the number in raw_input with the parsed number.
1348   string raw_input_copy(number.raw_input());
1349   // Normalize punctuation. We retain number grouping symbols such as " " only.
1350   NormalizeHelper(reg_exps_->all_plus_number_grouping_symbols_, true,
1351                   &raw_input_copy);
1352   // Now we trim everything before the first three digits in the parsed number.
1353   // We choose three because all valid alpha numbers have 3 digits at the start
1354   // - if it does not, then we don't trim anything at all. Similarly, if the
1355   // national number was less than three digits, we don't trim anything at all.
1356   string national_number;
1357   GetNationalSignificantNumber(number, &national_number);
1358   if (national_number.length() > 3) {
1359     size_t first_national_number_digit =
1360         raw_input_copy.find(national_number.substr(0, 3));
1361     if (first_national_number_digit != string::npos) {
1362       raw_input_copy = raw_input_copy.substr(first_national_number_digit);
1363     }
1364   }
1365   const PhoneMetadata* metadata = GetMetadataForRegion(calling_from);
1366   if (country_code == kNanpaCountryCode) {
1367     if (IsNANPACountry(calling_from)) {
1368       StrAppend(formatted_number, country_code, " ", raw_input_copy);
1369       return;
1370     }
1371   } else if (metadata &&
1372              country_code == GetCountryCodeForValidRegion(calling_from)) {
1373     const NumberFormat* formatting_pattern =
1374         ChooseFormattingPatternForNumber(metadata->number_format(),
1375                                          national_number);
1376     if (!formatting_pattern) {
1377       // If no pattern above is matched, we format the original input.
1378       formatted_number->assign(raw_input_copy);
1379       return;
1380     }
1381     NumberFormat new_format;
1382     new_format.MergeFrom(*formatting_pattern);
1383     // The first group is the first group of digits that the user wrote
1384     // together.
1385     new_format.set_pattern("(\\d+)(.*)");
1386     // Here we just concatenate them back together after the national prefix
1387     // has been fixed.
1388     new_format.set_format("$1$2");
1389     // Now we format using this pattern instead of the default pattern, but
1390     // with the national prefix prefixed if necessary.
1391     // This will not work in the cases where the pattern (and not the
1392     // leading digits) decide whether a national prefix needs to be used, since
1393     // we have overridden the pattern to match anything, but that is not the
1394     // case in the metadata to date.
1395     FormatNsnUsingPattern(raw_input_copy, new_format, NATIONAL,
1396                           formatted_number);
1397     return;
1398   }
1399
1400   string international_prefix_for_formatting;
1401   // If an unsupported region-calling-from is entered, or a country with
1402   // multiple international prefixes, the international format of the number is
1403   // returned, unless there is a preferred international prefix.
1404   if (metadata) {
1405     const string& international_prefix = metadata->international_prefix();
1406     international_prefix_for_formatting =
1407         reg_exps_->unique_international_prefix_->FullMatch(international_prefix)
1408         ? international_prefix
1409         : metadata->preferred_international_prefix();
1410   }
1411   if (!international_prefix_for_formatting.empty()) {
1412     StrAppend(formatted_number, international_prefix_for_formatting, " ",
1413               country_code, " ", raw_input_copy);
1414   } else {
1415     // Invalid region entered as country-calling-from (so no metadata was found
1416     // for it) or the region chosen has multiple international dialling
1417     // prefixes.
1418     LOG(WARNING) << "Trying to format number from invalid region "
1419                  << calling_from
1420                  << ". International formatting applied.";
1421     formatted_number->assign(raw_input_copy);
1422     PrefixNumberWithCountryCallingCode(country_code, INTERNATIONAL,
1423                                        formatted_number);
1424   }
1425 }
1426
1427 const NumberFormat* PhoneNumberUtil::ChooseFormattingPatternForNumber(
1428     const RepeatedPtrField<NumberFormat>& available_formats,
1429     const string& national_number) const {
1430   for (RepeatedPtrField<NumberFormat>::const_iterator
1431        it = available_formats.begin(); it != available_formats.end(); ++it) {
1432     int size = it->leading_digits_pattern_size();
1433     if (size > 0) {
1434       const scoped_ptr<RegExpInput> number_copy(
1435           reg_exps_->regexp_factory_->CreateInput(national_number));
1436       // We always use the last leading_digits_pattern, as it is the most
1437       // detailed.
1438       if (!reg_exps_->regexp_cache_->GetRegExp(
1439               it->leading_digits_pattern(size - 1)).Consume(
1440                   number_copy.get())) {
1441         continue;
1442       }
1443     }
1444     const RegExp& pattern_to_match(
1445         reg_exps_->regexp_cache_->GetRegExp(it->pattern()));
1446     if (pattern_to_match.FullMatch(national_number)) {
1447       return &(*it);
1448     }
1449   }
1450   return NULL;
1451 }
1452
1453 // Note that carrier_code is optional - if an empty string, no carrier code
1454 // replacement will take place.
1455 void PhoneNumberUtil::FormatNsnUsingPatternWithCarrier(
1456     const string& national_number,
1457     const NumberFormat& formatting_pattern,
1458     PhoneNumberUtil::PhoneNumberFormat number_format,
1459     const string& carrier_code,
1460     string* formatted_number) const {
1461   DCHECK(formatted_number);
1462   string number_format_rule(formatting_pattern.format());
1463   if (number_format == PhoneNumberUtil::NATIONAL &&
1464       carrier_code.length() > 0 &&
1465       formatting_pattern.domestic_carrier_code_formatting_rule().length() > 0) {
1466     // Replace the $CC in the formatting rule with the desired carrier code.
1467     string carrier_code_formatting_rule =
1468         formatting_pattern.domestic_carrier_code_formatting_rule();
1469     reg_exps_->carrier_code_pattern_->Replace(&carrier_code_formatting_rule,
1470                                               carrier_code);
1471     reg_exps_->first_group_capturing_pattern_->
1472         Replace(&number_format_rule, carrier_code_formatting_rule);
1473   } else {
1474     // Use the national prefix formatting rule instead.
1475     string national_prefix_formatting_rule =
1476         formatting_pattern.national_prefix_formatting_rule();
1477     if (number_format == PhoneNumberUtil::NATIONAL &&
1478         national_prefix_formatting_rule.length() > 0) {
1479       // Apply the national_prefix_formatting_rule as the formatting_pattern
1480       // contains only information on how the national significant number
1481       // should be formatted at this point.
1482       reg_exps_->first_group_capturing_pattern_->Replace(
1483           &number_format_rule, national_prefix_formatting_rule);
1484     }
1485   }
1486   formatted_number->assign(national_number);
1487
1488   const RegExp& pattern_to_match(
1489       reg_exps_->regexp_cache_->GetRegExp(formatting_pattern.pattern()));
1490   pattern_to_match.GlobalReplace(formatted_number, number_format_rule);
1491
1492   if (number_format == RFC3966) {
1493     // First consume any leading punctuation, if any was present.
1494     const scoped_ptr<RegExpInput> number(
1495         reg_exps_->regexp_factory_->CreateInput(*formatted_number));
1496     if (reg_exps_->separator_pattern_->Consume(number.get())) {
1497       formatted_number->assign(number->ToString());
1498     }
1499     // Then replace all separators with a "-".
1500     reg_exps_->separator_pattern_->GlobalReplace(formatted_number, "-");
1501   }
1502 }
1503
1504 // Simple wrapper of FormatNsnUsingPatternWithCarrier for the common case of
1505 // no carrier code.
1506 void PhoneNumberUtil::FormatNsnUsingPattern(
1507     const string& national_number,
1508     const NumberFormat& formatting_pattern,
1509     PhoneNumberUtil::PhoneNumberFormat number_format,
1510     string* formatted_number) const {
1511   DCHECK(formatted_number);
1512   FormatNsnUsingPatternWithCarrier(national_number, formatting_pattern,
1513                                    number_format, "", formatted_number);
1514 }
1515
1516 void PhoneNumberUtil::FormatNsn(const string& number,
1517                                 const PhoneMetadata& metadata,
1518                                 PhoneNumberFormat number_format,
1519                                 string* formatted_number) const {
1520   DCHECK(formatted_number);
1521   FormatNsnWithCarrier(number, metadata, number_format, "", formatted_number);
1522 }
1523
1524 // Note in some regions, the national number can be written in two completely
1525 // different ways depending on whether it forms part of the NATIONAL format or
1526 // INTERNATIONAL format. The number_format parameter here is used to specify
1527 // which format to use for those cases. If a carrier_code is specified, this
1528 // will be inserted into the formatted string to replace $CC.
1529 void PhoneNumberUtil::FormatNsnWithCarrier(const string& number,
1530                                            const PhoneMetadata& metadata,
1531                                            PhoneNumberFormat number_format,
1532                                            const string& carrier_code,
1533                                            string* formatted_number) const {
1534   DCHECK(formatted_number);
1535   // When the intl_number_formats exists, we use that to format national number
1536   // for the INTERNATIONAL format instead of using the number_formats.
1537   const RepeatedPtrField<NumberFormat> available_formats =
1538       (metadata.intl_number_format_size() == 0 || number_format == NATIONAL)
1539       ? metadata.number_format()
1540       : metadata.intl_number_format();
1541   const NumberFormat* formatting_pattern =
1542       ChooseFormattingPatternForNumber(available_formats, number);
1543   if (!formatting_pattern) {
1544     formatted_number->assign(number);
1545   } else {
1546     FormatNsnUsingPatternWithCarrier(number, *formatting_pattern, number_format,
1547                                      carrier_code, formatted_number);
1548   }
1549 }
1550
1551 // Appends the formatted extension of a phone number, if the phone number had an
1552 // extension specified.
1553 void PhoneNumberUtil::MaybeAppendFormattedExtension(
1554     const PhoneNumber& number,
1555     const PhoneMetadata& metadata,
1556     PhoneNumberFormat number_format,
1557     string* formatted_number) const {
1558   DCHECK(formatted_number);
1559   if (number.has_extension() && number.extension().length() > 0) {
1560     if (number_format == RFC3966) {
1561       StrAppend(formatted_number, kRfc3966ExtnPrefix, number.extension());
1562     } else {
1563       if (metadata.has_preferred_extn_prefix()) {
1564         StrAppend(formatted_number, metadata.preferred_extn_prefix(),
1565                   number.extension());
1566       } else {
1567         StrAppend(formatted_number, kDefaultExtnPrefix, number.extension());
1568       }
1569     }
1570   }
1571 }
1572
1573 bool PhoneNumberUtil::IsNANPACountry(const string& region_code) const {
1574   return nanpa_regions_->find(region_code) != nanpa_regions_->end();
1575 }
1576
1577 // Returns the region codes that matches the specific country calling code. In
1578 // the case of no region code being found, region_codes will be left empty.
1579 void PhoneNumberUtil::GetRegionCodesForCountryCallingCode(
1580     int country_calling_code,
1581     list<string>* region_codes) const {
1582   DCHECK(region_codes);
1583   // Create a IntRegionsPair with the country_code passed in, and use it to
1584   // locate the pair with the same country_code in the sorted vector.
1585   IntRegionsPair target_pair;
1586   target_pair.first = country_calling_code;
1587   typedef vector<IntRegionsPair>::const_iterator ConstIterator;
1588   pair<ConstIterator, ConstIterator> range = equal_range(
1589       country_calling_code_to_region_code_map_->begin(),
1590       country_calling_code_to_region_code_map_->end(),
1591       target_pair, OrderByFirst());
1592   if (range.first != range.second) {
1593     region_codes->insert(region_codes->begin(),
1594                          range.first->second->begin(),
1595                          range.first->second->end());
1596   }
1597 }
1598
1599 // Returns the region code that matches the specific country calling code. In
1600 // the case of no region code being found, the unknown region code will be
1601 // returned.
1602 void PhoneNumberUtil::GetRegionCodeForCountryCode(
1603     int country_calling_code,
1604     string* region_code) const {
1605   DCHECK(region_code);
1606   list<string> region_codes;
1607
1608   GetRegionCodesForCountryCallingCode(country_calling_code, &region_codes);
1609   *region_code = (region_codes.size() > 0) ?
1610       region_codes.front() : RegionCode::GetUnknown();
1611 }
1612
1613 void PhoneNumberUtil::GetRegionCodeForNumber(const PhoneNumber& number,
1614                                              string* region_code) const {
1615   DCHECK(region_code);
1616   int country_calling_code = number.country_code();
1617   list<string> region_codes;
1618   GetRegionCodesForCountryCallingCode(country_calling_code, &region_codes);
1619   if (region_codes.size() == 0) {
1620     string number_string;
1621     GetNationalSignificantNumber(number, &number_string);
1622     LOG(WARNING) << "Missing/invalid country calling code ("
1623                  << country_calling_code
1624                  << ") for number " << number_string;
1625     *region_code = RegionCode::GetUnknown();
1626     return;
1627   }
1628   if (region_codes.size() == 1) {
1629     *region_code = region_codes.front();
1630   } else {
1631     GetRegionCodeForNumberFromRegionList(number, region_codes, region_code);
1632   }
1633 }
1634
1635 void PhoneNumberUtil::GetRegionCodeForNumberFromRegionList(
1636     const PhoneNumber& number, const list<string>& region_codes,
1637     string* region_code) const {
1638   DCHECK(region_code);
1639   string national_number;
1640   GetNationalSignificantNumber(number, &national_number);
1641   for (list<string>::const_iterator it = region_codes.begin();
1642        it != region_codes.end(); ++it) {
1643     // Metadata cannot be NULL because the region codes come from the country
1644     // calling code map.
1645     const PhoneMetadata* metadata = GetMetadataForRegion(*it);
1646     if (metadata->has_leading_digits()) {
1647       const scoped_ptr<RegExpInput> number(
1648           reg_exps_->regexp_factory_->CreateInput(national_number));
1649       if (reg_exps_->regexp_cache_->
1650               GetRegExp(metadata->leading_digits()).Consume(number.get())) {
1651         *region_code = *it;
1652         return;
1653       }
1654     } else if (GetNumberTypeHelper(national_number, *metadata,
1655                                    reg_exps_->regexp_cache_.get()) != UNKNOWN) {
1656       *region_code = *it;
1657       return;
1658     }
1659   }
1660   *region_code = RegionCode::GetUnknown();
1661 }
1662
1663 int PhoneNumberUtil::GetCountryCodeForRegion(const string& region_code) const {
1664   if (!IsValidRegionCode(region_code)) {
1665     LOG(WARNING) << "Invalid or unknown region code (" << region_code
1666                  << ") provided.";
1667     return 0;
1668   }
1669   return GetCountryCodeForValidRegion(region_code);
1670 }
1671
1672 int PhoneNumberUtil::GetCountryCodeForValidRegion(
1673     const string& region_code) const {
1674   const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
1675   return metadata->country_code();
1676 }
1677
1678 // Gets a valid fixed-line number for the specified region_code. Returns false
1679 // if the region was unknown or 001 (representing non-geographical regions), or
1680 // if no number exists.
1681 bool PhoneNumberUtil::GetExampleNumber(const string& region_code,
1682                                        PhoneNumber* number) const {
1683   DCHECK(number);
1684   return GetExampleNumberForType(region_code, FIXED_LINE, number);
1685 }
1686
1687 // Gets a valid number for the specified region_code and type.  Returns false if
1688 // the country was unknown or 001 (representing non-geographical regions), or if
1689 // no number exists.
1690 bool PhoneNumberUtil::GetExampleNumberForType(
1691     const string& region_code,
1692     PhoneNumberUtil::PhoneNumberType type,
1693     PhoneNumber* number) const {
1694   DCHECK(number);
1695   if (!IsValidRegionCode(region_code)) {
1696     LOG(WARNING) << "Invalid or unknown region code (" << region_code
1697                  << ") provided.";
1698     return false;
1699   }
1700   const PhoneMetadata* region_metadata = GetMetadataForRegion(region_code);
1701   const PhoneNumberDesc* desc = GetNumberDescByType(*region_metadata, type);
1702   if (desc && desc->has_example_number()) {
1703     ErrorType success = Parse(desc->example_number(), region_code, number);
1704     if (success == NO_PARSING_ERROR) {
1705       return true;
1706     } else {
1707       LOG(ERROR) << "Error parsing example number ("
1708                  << static_cast<int>(success) << ")";
1709     }
1710   }
1711   return false;
1712 }
1713
1714 bool PhoneNumberUtil::GetExampleNumberForNonGeoEntity(
1715     int country_calling_code, PhoneNumber* number) const {
1716   DCHECK(number);
1717   const PhoneMetadata* metadata =
1718       GetMetadataForNonGeographicalRegion(country_calling_code);
1719   if (metadata) {
1720     const PhoneNumberDesc& desc = metadata->general_desc();
1721     if (desc.has_example_number()) {
1722       ErrorType success = Parse(StrCat(kPlusSign,
1723                                        SimpleItoa(country_calling_code),
1724                                        desc.example_number()),
1725                                 RegionCode::ZZ(), number);
1726       if (success == NO_PARSING_ERROR) {
1727         return true;
1728       } else {
1729         LOG(ERROR) << "Error parsing example number ("
1730                    << static_cast<int>(success) << ")";
1731       }
1732     }
1733   } else {
1734     LOG(WARNING) << "Invalid or unknown country calling code provided: "
1735                  << country_calling_code;
1736   }
1737   return false;
1738 }
1739
1740 PhoneNumberUtil::ErrorType PhoneNumberUtil::Parse(const string& number_to_parse,
1741                                                   const string& default_region,
1742                                                   PhoneNumber* number) const {
1743   DCHECK(number);
1744   return ParseHelper(number_to_parse, default_region, false, true, number);
1745 }
1746
1747 PhoneNumberUtil::ErrorType PhoneNumberUtil::ParseAndKeepRawInput(
1748     const string& number_to_parse,
1749     const string& default_region,
1750     PhoneNumber* number) const {
1751   DCHECK(number);
1752   return ParseHelper(number_to_parse, default_region, true, true, number);
1753 }
1754
1755 // Checks to see that the region code used is valid, or if it is not valid, that
1756 // the number to parse starts with a + symbol so that we can attempt to infer
1757 // the country from the number. Returns false if it cannot use the region
1758 // provided and the region cannot be inferred.
1759 bool PhoneNumberUtil::CheckRegionForParsing(
1760     const string& number_to_parse,
1761     const string& default_region) const {
1762   if (!IsValidRegionCode(default_region) && !number_to_parse.empty()) {
1763     const scoped_ptr<RegExpInput> number(
1764         reg_exps_->regexp_factory_->CreateInput(number_to_parse));
1765     if (!reg_exps_->plus_chars_pattern_->Consume(number.get())) {
1766       return false;
1767     }
1768   }
1769   return true;
1770 }
1771
1772 // Converts number_to_parse to a form that we can parse and write it to
1773 // national_number if it is written in RFC3966; otherwise extract a possible
1774 // number out of it and write to national_number.
1775 void PhoneNumberUtil::BuildNationalNumberForParsing(
1776     const string& number_to_parse, string* national_number) const {
1777   size_t index_of_phone_context = number_to_parse.find(kRfc3966PhoneContext);
1778   if (index_of_phone_context != string::npos) {
1779     int phone_context_start =
1780         index_of_phone_context + strlen(kRfc3966PhoneContext);
1781     // If the phone context contains a phone number prefix, we need to capture
1782     // it, whereas domains will be ignored.
1783     if (number_to_parse.at(phone_context_start) == kPlusSign[0]) {
1784       // Additional parameters might follow the phone context. If so, we will
1785       // remove them here because the parameters after phone context are not
1786       // important for parsing the phone number.
1787       size_t phone_context_end = number_to_parse.find(';', phone_context_start);
1788       if (phone_context_end != string::npos) {
1789         StrAppend(
1790             national_number, number_to_parse.substr(
1791                 phone_context_start, phone_context_end - phone_context_start));
1792       } else {
1793         StrAppend(national_number, number_to_parse.substr(phone_context_start));
1794       }
1795     }
1796
1797     // Now append everything between the "tel:" prefix and the phone-context.
1798     // This should include the national number, an optional extension or
1799     // isdn-subaddress component.
1800     int end_of_rfc_prefix =
1801         number_to_parse.find(kRfc3966Prefix) + strlen(kRfc3966Prefix);
1802     StrAppend(
1803         national_number,
1804         number_to_parse.substr(end_of_rfc_prefix,
1805                                index_of_phone_context - end_of_rfc_prefix));
1806   } else {
1807     // Extract a possible number from the string passed in (this strips leading
1808     // characters that could not be the start of a phone number.)
1809     ExtractPossibleNumber(number_to_parse, national_number);
1810   }
1811
1812   // Delete the isdn-subaddress and everything after it if it is present. Note
1813   // extension won't appear at the same time with isdn-subaddress according to
1814   // paragraph 5.3 of the RFC3966 spec.
1815   size_t index_of_isdn = national_number->find(kRfc3966IsdnSubaddress);
1816   if (index_of_isdn != string::npos) {
1817     national_number->erase(index_of_isdn);
1818   }
1819   // If both phone context and isdn-subaddress are absent but other parameters
1820   // are present, the parameters are left in nationalNumber. This is because
1821   // we are concerned about deleting content from a potential number string
1822   // when there is no strong evidence that the number is actually written in
1823   // RFC3966.
1824 }
1825
1826 PhoneNumberUtil::ErrorType PhoneNumberUtil::ParseHelper(
1827     const string& number_to_parse,
1828     const string& default_region,
1829     bool keep_raw_input,
1830     bool check_region,
1831     PhoneNumber* phone_number) const {
1832   DCHECK(phone_number);
1833
1834   string national_number;
1835   BuildNationalNumberForParsing(number_to_parse, &national_number);
1836
1837   if (!IsViablePhoneNumber(national_number)) {
1838     VLOG(2) << "The string supplied did not seem to be a phone number.";
1839     return NOT_A_NUMBER;
1840   }
1841
1842   if (check_region &&
1843       !CheckRegionForParsing(national_number, default_region)) {
1844     VLOG(1) << "Missing or invalid default country.";
1845     return INVALID_COUNTRY_CODE_ERROR;
1846   }
1847   PhoneNumber temp_number;
1848   if (keep_raw_input) {
1849     temp_number.set_raw_input(number_to_parse);
1850   }
1851   // Attempt to parse extension first, since it doesn't require country-specific
1852   // data and we want to have the non-normalised number here.
1853   string extension;
1854   MaybeStripExtension(&national_number, &extension);
1855   if (!extension.empty()) {
1856     temp_number.set_extension(extension);
1857   }
1858   const PhoneMetadata* country_metadata = GetMetadataForRegion(default_region);
1859   // Check to see if the number is given in international format so we know
1860   // whether this number is from the default country or not.
1861   string normalized_national_number(national_number);
1862   ErrorType country_code_error =
1863       MaybeExtractCountryCode(country_metadata, keep_raw_input,
1864                               &normalized_national_number, &temp_number);
1865   if (country_code_error != NO_PARSING_ERROR) {
1866      const scoped_ptr<RegExpInput> number_string_piece(
1867         reg_exps_->regexp_factory_->CreateInput(national_number));
1868     if ((country_code_error == INVALID_COUNTRY_CODE_ERROR) &&
1869         (reg_exps_->plus_chars_pattern_->Consume(number_string_piece.get()))) {
1870       normalized_national_number.assign(number_string_piece->ToString());
1871       // Strip the plus-char, and try again.
1872       MaybeExtractCountryCode(country_metadata,
1873                               keep_raw_input,
1874                               &normalized_national_number,
1875                               &temp_number);
1876       if (temp_number.country_code() == 0) {
1877         return INVALID_COUNTRY_CODE_ERROR;
1878       }
1879     } else {
1880       return country_code_error;
1881     }
1882   }
1883   int country_code = temp_number.country_code();
1884   if (country_code != 0) {
1885     string phone_number_region;
1886     GetRegionCodeForCountryCode(country_code, &phone_number_region);
1887     if (phone_number_region != default_region) {
1888       country_metadata =
1889           GetMetadataForRegionOrCallingCode(country_code, phone_number_region);
1890     }
1891   } else if (country_metadata) {
1892     // If no extracted country calling code, use the region supplied instead.
1893     // Note that the national number was already normalized by
1894     // MaybeExtractCountryCode.
1895     country_code = country_metadata->country_code();
1896   }
1897   if (normalized_national_number.length() < kMinLengthForNsn) {
1898     VLOG(2) << "The string supplied is too short to be a phone number.";
1899     return TOO_SHORT_NSN;
1900   }
1901   if (country_metadata) {
1902     string* carrier_code = keep_raw_input ?
1903         temp_number.mutable_preferred_domestic_carrier_code() : NULL;
1904     MaybeStripNationalPrefixAndCarrierCode(*country_metadata,
1905                                            &normalized_national_number,
1906                                            carrier_code);
1907   }
1908   size_t normalized_national_number_length =
1909       normalized_national_number.length();
1910   if (normalized_national_number_length < kMinLengthForNsn) {
1911     VLOG(2) << "The string supplied is too short to be a phone number.";
1912     return TOO_SHORT_NSN;
1913   }
1914   if (normalized_national_number_length > kMaxLengthForNsn) {
1915     VLOG(2) << "The string supplied is too long to be a phone number.";
1916     return TOO_LONG_NSN;
1917   }
1918   temp_number.set_country_code(country_code);
1919   if (normalized_national_number[0] == '0') {
1920     temp_number.set_italian_leading_zero(true);
1921   }
1922   uint64 number_as_int;
1923   safe_strtou64(normalized_national_number, &number_as_int);
1924   temp_number.set_national_number(number_as_int);
1925   phone_number->MergeFrom(temp_number);
1926   return NO_PARSING_ERROR;
1927 }
1928
1929 // Attempts to extract a possible number from the string passed in. This
1930 // currently strips all leading characters that could not be used to start a
1931 // phone number. Characters that can be used to start a phone number are
1932 // defined in the valid_start_char_pattern. If none of these characters are
1933 // found in the number passed in, an empty string is returned. This function
1934 // also attempts to strip off any alternative extensions or endings if two or
1935 // more are present, such as in the case of: (530) 583-6985 x302/x2303. The
1936 // second extension here makes this actually two phone numbers, (530) 583-6985
1937 // x302 and (530) 583-6985 x2303. We remove the second extension so that the
1938 // first number is parsed correctly.
1939 void PhoneNumberUtil::ExtractPossibleNumber(const string& number,
1940                                             string* extracted_number) const {
1941   DCHECK(extracted_number);
1942
1943   UnicodeText number_as_unicode;
1944   number_as_unicode.PointToUTF8(number.data(), number.size());
1945   char current_char[5];
1946   int len;
1947   UnicodeText::const_iterator it;
1948   for (it = number_as_unicode.begin(); it != number_as_unicode.end(); ++it) {
1949     len = it.get_utf8(current_char);
1950     current_char[len] = '\0';
1951     if (reg_exps_->valid_start_char_pattern_->FullMatch(current_char)) {
1952       break;
1953     }
1954   }
1955
1956   if (it == number_as_unicode.end()) {
1957     // No valid start character was found. extracted_number should be set to
1958     // empty string.
1959     extracted_number->assign("");
1960     return;
1961   }
1962
1963   extracted_number->assign(
1964       UnicodeText::UTF8Substring(it, number_as_unicode.end()));
1965   TrimUnwantedEndChars(extracted_number);
1966   if (extracted_number->length() == 0) {
1967     return;
1968   }
1969
1970   VLOG(3) << "After stripping starting and trailing characters, left with: "
1971           << *extracted_number;
1972
1973   // Now remove any extra numbers at the end.
1974   reg_exps_->capture_up_to_second_number_start_pattern_->
1975       PartialMatch(*extracted_number, extracted_number);
1976 }
1977
1978 bool PhoneNumberUtil::IsPossibleNumber(const PhoneNumber& number) const {
1979   return IsPossibleNumberWithReason(number) == IS_POSSIBLE;
1980 }
1981
1982 bool PhoneNumberUtil::IsPossibleNumberForString(
1983     const string& number,
1984     const string& region_dialing_from) const {
1985   PhoneNumber number_proto;
1986   if (Parse(number, region_dialing_from, &number_proto) == NO_PARSING_ERROR) {
1987     return IsPossibleNumber(number_proto);
1988   } else {
1989     return false;
1990   }
1991 }
1992
1993 PhoneNumberUtil::ValidationResult PhoneNumberUtil::IsPossibleNumberWithReason(
1994     const PhoneNumber& number) const {
1995   string national_number;
1996   GetNationalSignificantNumber(number, &national_number);
1997   int country_code = number.country_code();
1998   // Note: For Russian Fed and NANPA numbers, we just use the rules from the
1999   // default region (US or Russia) since the GetRegionCodeForNumber will not
2000   // work if the number is possible but not valid. This would need to be
2001   // revisited if the possible number pattern ever differed between various
2002   // regions within those plans.
2003   if (!HasValidCountryCallingCode(country_code)) {
2004     return INVALID_COUNTRY_CODE;
2005   }
2006   string region_code;
2007   GetRegionCodeForCountryCode(country_code, &region_code);
2008   // Metadata cannot be NULL because the country calling code is valid.
2009   const PhoneMetadata* metadata =
2010       GetMetadataForRegionOrCallingCode(country_code, region_code);
2011   const PhoneNumberDesc& general_num_desc = metadata->general_desc();
2012   // Handling case of numbers with no metadata.
2013   if (!general_num_desc.has_national_number_pattern()) {
2014     size_t number_length = national_number.length();
2015     if (number_length < kMinLengthForNsn) {
2016       return TOO_SHORT;
2017     } else if (number_length > kMaxLengthForNsn) {
2018       return TOO_LONG;
2019     } else {
2020       return IS_POSSIBLE;
2021     }
2022   }
2023   const RegExp& possible_number_pattern = reg_exps_->regexp_cache_->GetRegExp(
2024       StrCat("(", general_num_desc.possible_number_pattern(), ")"));
2025   return TestNumberLengthAgainstPattern(possible_number_pattern,
2026                                         national_number);
2027 }
2028
2029 bool PhoneNumberUtil::TruncateTooLongNumber(PhoneNumber* number) const {
2030   if (IsValidNumber(*number)) {
2031     return true;
2032   }
2033   PhoneNumber number_copy(*number);
2034   uint64 national_number = number->national_number();
2035   do {
2036     national_number /= 10;
2037     number_copy.set_national_number(national_number);
2038     if (IsPossibleNumberWithReason(number_copy) == TOO_SHORT ||
2039         national_number == 0) {
2040       return false;
2041     }
2042   } while (!IsValidNumber(number_copy));
2043   number->set_national_number(national_number);
2044   return true;
2045 }
2046
2047 PhoneNumberUtil::PhoneNumberType PhoneNumberUtil::GetNumberType(
2048     const PhoneNumber& number) const {
2049   string region_code;
2050   GetRegionCodeForNumber(number, &region_code);
2051   const PhoneMetadata* metadata =
2052       GetMetadataForRegionOrCallingCode(number.country_code(), region_code);
2053   if (!metadata) {
2054     return UNKNOWN;
2055   }
2056   string national_significant_number;
2057   GetNationalSignificantNumber(number, &national_significant_number);
2058   return GetNumberTypeHelper(national_significant_number,
2059                              *metadata,
2060                              reg_exps_->regexp_cache_.get());
2061 }
2062
2063 bool PhoneNumberUtil::IsValidNumber(const PhoneNumber& number) const {
2064   string region_code;
2065   GetRegionCodeForNumber(number, &region_code);
2066   return IsValidNumberForRegion(number, region_code);
2067 }
2068
2069 bool PhoneNumberUtil::IsValidNumberForRegion(const PhoneNumber& number,
2070                                              const string& region_code) const {
2071   int country_code = number.country_code();
2072   const PhoneMetadata* metadata =
2073       GetMetadataForRegionOrCallingCode(country_code, region_code);
2074   if (!metadata ||
2075       ((kRegionCodeForNonGeoEntity != region_code) &&
2076        country_code != GetCountryCodeForValidRegion(region_code))) {
2077     // Either the region code was invalid, or the country calling code for this
2078     // number does not match that of the region code.
2079     return false;
2080   }
2081   const PhoneNumberDesc& general_desc = metadata->general_desc();
2082   string national_number;
2083   GetNationalSignificantNumber(number, &national_number);
2084
2085   // For regions where we don't have metadata for PhoneNumberDesc, we treat
2086   // any number passed in as a valid number if its national significant number
2087   // is between the minimum and maximum lengths defined by ITU for a national
2088   // significant number.
2089   if (!general_desc.has_national_number_pattern()) {
2090     VLOG(3) << "Validating number with incomplete metadata.";
2091     size_t number_length = national_number.length();
2092     return number_length > kMinLengthForNsn &&
2093         number_length <= kMaxLengthForNsn;
2094   }
2095   return GetNumberTypeHelper(national_number, *metadata,
2096                              reg_exps_->regexp_cache_.get()) != UNKNOWN;
2097 }
2098
2099 bool PhoneNumberUtil::IsNumberGeographical(
2100     const PhoneNumber& phone_number) const {
2101   PhoneNumberType number_type = GetNumberType(phone_number);
2102   // TODO: Include mobile phone numbers from countries like
2103   // Indonesia, which has some mobile numbers that are geographical.
2104   return number_type == PhoneNumberUtil::FIXED_LINE ||
2105       number_type == PhoneNumberUtil::FIXED_LINE_OR_MOBILE;
2106 }
2107
2108 bool PhoneNumberUtil::IsLeadingZeroPossible(int country_calling_code) const {
2109   string region_code;
2110   GetRegionCodeForCountryCode(country_calling_code, &region_code);
2111   const PhoneMetadata* main_metadata_for_calling_code =
2112       GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
2113   if (!main_metadata_for_calling_code) return false;
2114   return main_metadata_for_calling_code->leading_zero_possible();
2115 }
2116
2117 void PhoneNumberUtil::GetNationalSignificantNumber(
2118     const PhoneNumber& number,
2119     string* national_number) const {
2120   DCHECK(national_number);
2121   // If a leading zero has been set, we prefix this now. Note this is not a
2122   // national prefix.
2123   StrAppend(national_number, number.italian_leading_zero() ? "0" : "");
2124   StrAppend(national_number, number.national_number());
2125 }
2126
2127 int PhoneNumberUtil::GetLengthOfGeographicalAreaCode(
2128     const PhoneNumber& number) const {
2129   string region_code;
2130   GetRegionCodeForNumber(number, &region_code);
2131   const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
2132   if (!metadata) {
2133     return 0;
2134   }
2135   // If a country doesn't use a national prefix, and this number doesn't have an
2136   // Italian leading zero, we assume it is a closed dialling plan with no area
2137   // codes.
2138   if (!metadata->has_national_prefix() && !number.italian_leading_zero()) {
2139     return 0;
2140   }
2141
2142   if (!IsNumberGeographical(number)) {
2143     return 0;
2144   }
2145
2146   return GetLengthOfNationalDestinationCode(number);
2147 }
2148
2149 int PhoneNumberUtil::GetLengthOfNationalDestinationCode(
2150     const PhoneNumber& number) const {
2151   PhoneNumber copied_proto(number);
2152   if (number.has_extension()) {
2153     // Clear the extension so it's not included when formatting.
2154     copied_proto.clear_extension();
2155   }
2156
2157   string formatted_number;
2158   Format(copied_proto, INTERNATIONAL, &formatted_number);
2159   const scoped_ptr<RegExpInput> i18n_number(
2160       reg_exps_->regexp_factory_->CreateInput(formatted_number));
2161   string digit_group;
2162   string ndc;
2163   string third_group;
2164   for (int i = 0; i < 3; ++i) {
2165     if (!reg_exps_->capturing_ascii_digits_pattern_->FindAndConsume(
2166             i18n_number.get(), &digit_group)) {
2167       // We should find at least three groups.
2168       return 0;
2169     }
2170     if (i == 1) {
2171       ndc = digit_group;
2172     } else if (i == 2) {
2173       third_group = digit_group;
2174     }
2175   }
2176   string region_code;
2177   GetRegionCodeForCountryCode(number.country_code(), &region_code);
2178   if (region_code == "AR" &&
2179       GetNumberType(number) == MOBILE) {
2180     // Argentinian mobile numbers, when formatted in the international format,
2181     // are in the form of +54 9 NDC XXXX.... As a result, we take the length of
2182     // the third group (NDC) and add 1 for the digit 9, which also forms part of
2183     // the national significant number.
2184     return third_group.size() + 1;
2185   }
2186   return ndc.size();
2187 }
2188
2189 void PhoneNumberUtil::NormalizeDigitsOnly(string* number) const {
2190   DCHECK(number);
2191   const RegExp& non_digits_pattern = reg_exps_->regexp_cache_->GetRegExp(
2192       StrCat("[^", kDigits, "]"));
2193   // Delete everything that isn't valid digits.
2194   non_digits_pattern.GlobalReplace(number, "");
2195   // Normalize all decimal digits to ASCII digits.
2196   number->assign(NormalizeUTF8::NormalizeDecimalDigits(*number));
2197 }
2198
2199 bool PhoneNumberUtil::IsAlphaNumber(const string& number) const {
2200   if (!IsViablePhoneNumber(number)) {
2201     // Number is too short, or doesn't match the basic phone number pattern.
2202     return false;
2203   }
2204   // Copy the number, since we are going to try and strip the extension from it.
2205   string number_copy(number);
2206   string extension;
2207   MaybeStripExtension(&number_copy, &extension);
2208   return reg_exps_->valid_alpha_phone_pattern_->FullMatch(number_copy);
2209 }
2210
2211 void PhoneNumberUtil::ConvertAlphaCharactersInNumber(string* number) const {
2212   DCHECK(number);
2213   NormalizeHelper(reg_exps_->alpha_phone_mappings_, false, number);
2214 }
2215
2216 // Normalizes a string of characters representing a phone number. This performs
2217 // the following conversions:
2218 //   - Punctuation is stripped.
2219 //   For ALPHA/VANITY numbers:
2220 //   - Letters are converted to their numeric representation on a telephone
2221 //     keypad. The keypad used here is the one defined in ITU Recommendation
2222 //     E.161. This is only done if there are 3 or more letters in the number, to
2223 //     lessen the risk that such letters are typos.
2224 //   For other numbers:
2225 //   - Wide-ascii digits are converted to normal ASCII (European) digits.
2226 //   - Arabic-Indic numerals are converted to European numerals.
2227 //   - Spurious alpha characters are stripped.
2228 void PhoneNumberUtil::Normalize(string* number) const {
2229   DCHECK(number);
2230   if (reg_exps_->valid_alpha_phone_pattern_->PartialMatch(*number)) {
2231     NormalizeHelper(reg_exps_->alpha_phone_mappings_, true, number);
2232   }
2233   NormalizeDigitsOnly(number);
2234 }
2235
2236 // Checks to see if the string of characters could possibly be a phone number at
2237 // all. At the moment, checks to see that the string begins with at least 3
2238 // digits, ignoring any punctuation commonly found in phone numbers.  This
2239 // method does not require the number to be normalized in advance - but does
2240 // assume that leading non-number symbols have been removed, such as by the
2241 // method ExtractPossibleNumber.
2242 bool PhoneNumberUtil::IsViablePhoneNumber(const string& number) const {
2243   if (number.length() < kMinLengthForNsn) {
2244     VLOG(2) << "Number too short to be viable:" << number;
2245     return false;
2246   }
2247   return reg_exps_->valid_phone_number_pattern_->FullMatch(number);
2248 }
2249
2250 // Strips the IDD from the start of the number if present. Helper function used
2251 // by MaybeStripInternationalPrefixAndNormalize.
2252 bool PhoneNumberUtil::ParsePrefixAsIdd(const RegExp& idd_pattern,
2253                                        string* number) const {
2254   DCHECK(number);
2255   const scoped_ptr<RegExpInput> number_copy(
2256       reg_exps_->regexp_factory_->CreateInput(*number));
2257   // First attempt to strip the idd_pattern at the start, if present. We make a
2258   // copy so that we can revert to the original string if necessary.
2259   if (idd_pattern.Consume(number_copy.get())) {
2260     // Only strip this if the first digit after the match is not a 0, since
2261     // country calling codes cannot begin with 0.
2262     string extracted_digit;
2263     if (reg_exps_->capturing_digit_pattern_->PartialMatch(
2264             number_copy->ToString(), &extracted_digit)) {
2265       NormalizeDigitsOnly(&extracted_digit);
2266       if (extracted_digit == "0") {
2267         return false;
2268       }
2269     }
2270     number->assign(number_copy->ToString());
2271     return true;
2272   }
2273   return false;
2274 }
2275
2276 // Strips any international prefix (such as +, 00, 011) present in the number
2277 // provided, normalizes the resulting number, and indicates if an international
2278 // prefix was present.
2279 //
2280 // possible_idd_prefix represents the international direct dialing prefix from
2281 // the region we think this number may be dialed in.
2282 // Returns true if an international dialing prefix could be removed from the
2283 // number, otherwise false if the number did not seem to be in international
2284 // format.
2285 PhoneNumber::CountryCodeSource
2286 PhoneNumberUtil::MaybeStripInternationalPrefixAndNormalize(
2287     const string& possible_idd_prefix,
2288     string* number) const {
2289   DCHECK(number);
2290   if (number->empty()) {
2291     return PhoneNumber::FROM_DEFAULT_COUNTRY;
2292   }
2293   const scoped_ptr<RegExpInput> number_string_piece(
2294       reg_exps_->regexp_factory_->CreateInput(*number));
2295   if (reg_exps_->plus_chars_pattern_->Consume(number_string_piece.get())) {
2296     number->assign(number_string_piece->ToString());
2297     // Can now normalize the rest of the number since we've consumed the "+"
2298     // sign at the start.
2299     Normalize(number);
2300     return PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN;
2301   }
2302   // Attempt to parse the first digits as an international prefix.
2303   const RegExp& idd_pattern =
2304       reg_exps_->regexp_cache_->GetRegExp(possible_idd_prefix);
2305   Normalize(number);
2306   return ParsePrefixAsIdd(idd_pattern, number)
2307       ? PhoneNumber::FROM_NUMBER_WITH_IDD
2308       : PhoneNumber::FROM_DEFAULT_COUNTRY;
2309 }
2310
2311 // Strips any national prefix (such as 0, 1) present in the number provided.
2312 // The number passed in should be the normalized telephone number that we wish
2313 // to strip any national dialing prefix from. The metadata should be for the
2314 // region that we think this number is from. Returns true if a national prefix
2315 // and/or carrier code was stripped.
2316 bool PhoneNumberUtil::MaybeStripNationalPrefixAndCarrierCode(
2317     const PhoneMetadata& metadata,
2318     string* number,
2319     string* carrier_code) const {
2320   DCHECK(number);
2321   string carrier_code_temp;
2322   const string& possible_national_prefix =
2323       metadata.national_prefix_for_parsing();
2324   if (number->empty() || possible_national_prefix.empty()) {
2325     // Early return for numbers of zero length or with no national prefix
2326     // possible.
2327     return false;
2328   }
2329   // We use two copies here since Consume modifies the phone number, and if the
2330   // first if-clause fails the number will already be changed.
2331   const scoped_ptr<RegExpInput> number_copy(
2332       reg_exps_->regexp_factory_->CreateInput(*number));
2333   const scoped_ptr<RegExpInput> number_copy_without_transform(
2334       reg_exps_->regexp_factory_->CreateInput(*number));
2335   string number_string_copy(*number);
2336   string captured_part_of_prefix;
2337   const RegExp& national_number_rule = reg_exps_->regexp_cache_->GetRegExp(
2338       metadata.general_desc().national_number_pattern());
2339   // Check if the original number is viable.
2340   bool is_viable_original_number = national_number_rule.FullMatch(*number);
2341   // Attempt to parse the first digits as a national prefix. We make a
2342   // copy so that we can revert to the original string if necessary.
2343   const string& transform_rule = metadata.national_prefix_transform_rule();
2344   const RegExp& possible_national_prefix_pattern =
2345       reg_exps_->regexp_cache_->GetRegExp(possible_national_prefix);
2346   if (!transform_rule.empty() &&
2347       (possible_national_prefix_pattern.Consume(
2348           number_copy.get(), &carrier_code_temp, &captured_part_of_prefix) ||
2349        possible_national_prefix_pattern.Consume(
2350            number_copy.get(), &captured_part_of_prefix)) &&
2351       !captured_part_of_prefix.empty()) {
2352     // If this succeeded, then we must have had a transform rule and there must
2353     // have been some part of the prefix that we captured.
2354     // We make the transformation and check that the resultant number is still
2355     // viable. If so, replace the number and return.
2356     possible_national_prefix_pattern.Replace(&number_string_copy,
2357                                              transform_rule);
2358     if (is_viable_original_number &&
2359         !national_number_rule.FullMatch(number_string_copy)) {
2360       return false;
2361     }
2362     number->assign(number_string_copy);
2363     if (carrier_code) {
2364       carrier_code->assign(carrier_code_temp);
2365     }
2366   } else if (possible_national_prefix_pattern.Consume(
2367                  number_copy_without_transform.get(), &carrier_code_temp) ||
2368              possible_national_prefix_pattern.Consume(
2369                  number_copy_without_transform.get())) {
2370     VLOG(4) << "Parsed the first digits as a national prefix.";
2371     // If captured_part_of_prefix is empty, this implies nothing was captured by
2372     // the capturing groups in possible_national_prefix; therefore, no
2373     // transformation is necessary, and we just remove the national prefix.
2374     const string number_copy_as_string =
2375         number_copy_without_transform->ToString();
2376     if (is_viable_original_number &&
2377         !national_number_rule.FullMatch(number_copy_as_string)) {
2378       return false;
2379     }
2380     number->assign(number_copy_as_string);
2381     if (carrier_code) {
2382       carrier_code->assign(carrier_code_temp);
2383     }
2384   } else {
2385     return false;
2386     VLOG(4) << "The first digits did not match the national prefix.";
2387   }
2388   return true;
2389 }
2390
2391 // Strips any extension (as in, the part of the number dialled after the call is
2392 // connected, usually indicated with extn, ext, x or similar) from the end of
2393 // the number, and returns it. The number passed in should be non-normalized.
2394 bool PhoneNumberUtil::MaybeStripExtension(string* number, string* extension)
2395     const {
2396   DCHECK(number);
2397   DCHECK(extension);
2398   // There are three extension capturing groups in the regular expression.
2399   string possible_extension_one;
2400   string possible_extension_two;
2401   string possible_extension_three;
2402   string number_copy(*number);
2403   const scoped_ptr<RegExpInput> number_copy_as_regexp_input(
2404       reg_exps_->regexp_factory_->CreateInput(number_copy));
2405   if (reg_exps_->extn_pattern_->Consume(number_copy_as_regexp_input.get(),
2406                             false,
2407                             &possible_extension_one,
2408                             &possible_extension_two,
2409                             &possible_extension_three)) {
2410     // Replace the extensions in the original string here.
2411     reg_exps_->extn_pattern_->Replace(&number_copy, "");
2412     VLOG(4) << "Found an extension. Possible extension one: "
2413             << possible_extension_one
2414             << ". Possible extension two: " << possible_extension_two
2415             << ". Possible extension three: " << possible_extension_three
2416             << ". Remaining number: " << number_copy;
2417     // If we find a potential extension, and the number preceding this is a
2418     // viable number, we assume it is an extension.
2419     if ((!possible_extension_one.empty() || !possible_extension_two.empty() ||
2420          !possible_extension_three.empty()) &&
2421         IsViablePhoneNumber(number_copy)) {
2422       number->assign(number_copy);
2423       if (!possible_extension_one.empty()) {
2424         extension->assign(possible_extension_one);
2425       } else if (!possible_extension_two.empty()) {
2426         extension->assign(possible_extension_two);
2427       } else if (!possible_extension_three.empty()) {
2428         extension->assign(possible_extension_three);
2429       }
2430       return true;
2431     }
2432   }
2433   return false;
2434 }
2435
2436 // Extracts country calling code from national_number, and returns it. It
2437 // assumes that the leading plus sign or IDD has already been removed. Returns 0
2438 // if national_number doesn't start with a valid country calling code, and
2439 // leaves national_number unmodified. Assumes the national_number is at least 3
2440 // characters long.
2441 int PhoneNumberUtil::ExtractCountryCode(string* national_number) const {
2442   int potential_country_code;
2443   if (national_number->empty() || (national_number->at(0) == '0')) {
2444     // Country codes do not begin with a '0'.
2445     return 0;
2446   }
2447   for (size_t i = 1; i <= kMaxLengthCountryCode; ++i) {
2448     safe_strto32(national_number->substr(0, i), &potential_country_code);
2449     string region_code;
2450     GetRegionCodeForCountryCode(potential_country_code, &region_code);
2451     if (region_code != RegionCode::GetUnknown()) {
2452       national_number->erase(0, i);
2453       return potential_country_code;
2454     }
2455   }
2456   return 0;
2457 }
2458
2459 // Tries to extract a country calling code from a number. Country calling codes
2460 // are extracted in the following ways:
2461 //   - by stripping the international dialing prefix of the region the person
2462 //   is dialing from, if this is present in the number, and looking at the next
2463 //   digits
2464 //   - by stripping the '+' sign if present and then looking at the next digits
2465 //   - by comparing the start of the number and the country calling code of the
2466 //   default region. If the number is not considered possible for the numbering
2467 //   plan of the default region initially, but starts with the country calling
2468 //   code of this region, validation will be reattempted after stripping this
2469 //   country calling code. If this number is considered a possible number, then
2470 //   the first digits will be considered the country calling code and removed as
2471 //   such.
2472 //
2473 //   Returns NO_PARSING_ERROR if a country calling code was successfully
2474 //   extracted or none was present, or the appropriate error otherwise, such as
2475 //   if a + was present but it was not followed by a valid country calling code.
2476 //   If NO_PARSING_ERROR is returned, the national_number without the country
2477 //   calling code is populated, and the country_code of the phone_number passed
2478 //   in is set to the country calling code if found, otherwise to 0.
2479 PhoneNumberUtil::ErrorType PhoneNumberUtil::MaybeExtractCountryCode(
2480     const PhoneMetadata* default_region_metadata,
2481     bool keep_raw_input,
2482     string* national_number,
2483     PhoneNumber* phone_number) const {
2484   DCHECK(national_number);
2485   DCHECK(phone_number);
2486   // Set the default prefix to be something that will never match if there is no
2487   // default region.
2488   string possible_country_idd_prefix = default_region_metadata
2489       ?  default_region_metadata->international_prefix()
2490       : "NonMatch";
2491   PhoneNumber::CountryCodeSource country_code_source =
2492       MaybeStripInternationalPrefixAndNormalize(possible_country_idd_prefix,
2493                                                 national_number);
2494   if (keep_raw_input) {
2495     phone_number->set_country_code_source(country_code_source);
2496   }
2497   if (country_code_source != PhoneNumber::FROM_DEFAULT_COUNTRY) {
2498     if (national_number->length() <= kMinLengthForNsn) {
2499       VLOG(2) << "Phone number had an IDD, but after this was not "
2500               << "long enough to be a viable phone number.";
2501       return TOO_SHORT_AFTER_IDD;
2502     }
2503     int potential_country_code = ExtractCountryCode(national_number);
2504     if (potential_country_code != 0) {
2505       phone_number->set_country_code(potential_country_code);
2506       return NO_PARSING_ERROR;
2507     }
2508     // If this fails, they must be using a strange country calling code that we
2509     // don't recognize, or that doesn't exist.
2510     return INVALID_COUNTRY_CODE_ERROR;
2511   } else if (default_region_metadata) {
2512     // Check to see if the number starts with the country calling code for the
2513     // default region. If so, we remove the country calling code, and do some
2514     // checks on the validity of the number before and after.
2515     int default_country_code = default_region_metadata->country_code();
2516     string default_country_code_string(SimpleItoa(default_country_code));
2517     VLOG(4) << "Possible country calling code: " << default_country_code_string;
2518     string potential_national_number;
2519     if (TryStripPrefixString(*national_number,
2520                              default_country_code_string,
2521                              &potential_national_number)) {
2522       const PhoneNumberDesc& general_num_desc =
2523           default_region_metadata->general_desc();
2524       const RegExp& valid_number_pattern =
2525           reg_exps_->regexp_cache_->GetRegExp(
2526               general_num_desc.national_number_pattern());
2527       MaybeStripNationalPrefixAndCarrierCode(*default_region_metadata,
2528                                              &potential_national_number,
2529                                              NULL);
2530       VLOG(4) << "Number without country calling code prefix: "
2531               << potential_national_number;
2532       const RegExp& possible_number_pattern =
2533           reg_exps_->regexp_cache_->GetRegExp(
2534               StrCat("(", general_num_desc.possible_number_pattern(), ")"));
2535       // If the number was not valid before but is valid now, or if it was too
2536       // long before, we consider the number with the country code stripped to
2537       // be a better result and keep that instead.
2538       if ((!valid_number_pattern.FullMatch(*national_number) &&
2539            valid_number_pattern.FullMatch(potential_national_number)) ||
2540            TestNumberLengthAgainstPattern(possible_number_pattern,
2541                                           *national_number) == TOO_LONG) {
2542         national_number->assign(potential_national_number);
2543         if (keep_raw_input) {
2544           phone_number->set_country_code_source(
2545               PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN);
2546         }
2547         phone_number->set_country_code(default_country_code);
2548         return NO_PARSING_ERROR;
2549       }
2550     }
2551   }
2552   // No country calling code present. Set the country_code to 0.
2553   phone_number->set_country_code(0);
2554   return NO_PARSING_ERROR;
2555 }
2556
2557 PhoneNumberUtil::MatchType PhoneNumberUtil::IsNumberMatch(
2558     const PhoneNumber& first_number_in,
2559     const PhoneNumber& second_number_in) const {
2560   // Make copies of the phone number so that the numbers passed in are not
2561   // edited.
2562   PhoneNumber first_number(first_number_in);
2563   PhoneNumber second_number(second_number_in);
2564   // First clear raw_input and country_code_source and
2565   // preferred_domestic_carrier_code fields and any empty-string extensions so
2566   // that we can use the proto-buffer equality method.
2567   first_number.clear_raw_input();
2568   first_number.clear_country_code_source();
2569   first_number.clear_preferred_domestic_carrier_code();
2570   second_number.clear_raw_input();
2571   second_number.clear_country_code_source();
2572   second_number.clear_preferred_domestic_carrier_code();
2573   if (first_number.extension().empty()) {
2574     first_number.clear_extension();
2575   }
2576   if (second_number.extension().empty()) {
2577     second_number.clear_extension();
2578   }
2579   // Early exit if both had extensions and these are different.
2580   if (first_number.has_extension() && second_number.has_extension() &&
2581       first_number.extension() != second_number.extension()) {
2582     return NO_MATCH;
2583   }
2584   int first_number_country_code = first_number.country_code();
2585   int second_number_country_code = second_number.country_code();
2586   // Both had country calling code specified.
2587   if (first_number_country_code != 0 && second_number_country_code != 0) {
2588     if (ExactlySameAs(first_number, second_number)) {
2589       return EXACT_MATCH;
2590     } else if (first_number_country_code == second_number_country_code &&
2591                IsNationalNumberSuffixOfTheOther(first_number, second_number)) {
2592       // A SHORT_NSN_MATCH occurs if there is a difference because of the
2593       // presence or absence of an 'Italian leading zero', the presence or
2594       // absence of an extension, or one NSN being a shorter variant of the
2595       // other.
2596       return SHORT_NSN_MATCH;
2597     }
2598     // This is not a match.
2599     return NO_MATCH;
2600   }
2601   // Checks cases where one or both country calling codes were not specified. To
2602   // make equality checks easier, we first set the country_code fields to be
2603   // equal.
2604   first_number.set_country_code(second_number_country_code);
2605   // If all else was the same, then this is an NSN_MATCH.
2606   if (ExactlySameAs(first_number, second_number)) {
2607     return NSN_MATCH;
2608   }
2609   if (IsNationalNumberSuffixOfTheOther(first_number, second_number)) {
2610     return SHORT_NSN_MATCH;
2611   }
2612   return NO_MATCH;
2613 }
2614
2615 PhoneNumberUtil::MatchType PhoneNumberUtil::IsNumberMatchWithTwoStrings(
2616     const string& first_number,
2617     const string& second_number) const {
2618   PhoneNumber first_number_as_proto;
2619   ErrorType error_type =
2620       Parse(first_number, RegionCode::GetUnknown(), &first_number_as_proto);
2621   if (error_type == NO_PARSING_ERROR) {
2622     return IsNumberMatchWithOneString(first_number_as_proto, second_number);
2623   }
2624   if (error_type == INVALID_COUNTRY_CODE_ERROR) {
2625     PhoneNumber second_number_as_proto;
2626     ErrorType error_type = Parse(second_number, RegionCode::GetUnknown(),
2627                                  &second_number_as_proto);
2628     if (error_type == NO_PARSING_ERROR) {
2629       return IsNumberMatchWithOneString(second_number_as_proto, first_number);
2630     }
2631     if (error_type == INVALID_COUNTRY_CODE_ERROR) {
2632       error_type  = ParseHelper(first_number, RegionCode::GetUnknown(), false,
2633                                 false, &first_number_as_proto);
2634       if (error_type == NO_PARSING_ERROR) {
2635         error_type = ParseHelper(second_number, RegionCode::GetUnknown(), false,
2636                                  false, &second_number_as_proto);
2637         if (error_type == NO_PARSING_ERROR) {
2638           return IsNumberMatch(first_number_as_proto, second_number_as_proto);
2639         }
2640       }
2641     }
2642   }
2643   // One or more of the phone numbers we are trying to match is not a viable
2644   // phone number.
2645   return INVALID_NUMBER;
2646 }
2647
2648 PhoneNumberUtil::MatchType PhoneNumberUtil::IsNumberMatchWithOneString(
2649     const PhoneNumber& first_number,
2650     const string& second_number) const {
2651   // First see if the second number has an implicit country calling code, by
2652   // attempting to parse it.
2653   PhoneNumber second_number_as_proto;
2654   ErrorType error_type =
2655       Parse(second_number, RegionCode::GetUnknown(), &second_number_as_proto);
2656   if (error_type == NO_PARSING_ERROR) {
2657     return IsNumberMatch(first_number, second_number_as_proto);
2658   }
2659   if (error_type == INVALID_COUNTRY_CODE_ERROR) {
2660     // The second number has no country calling code. EXACT_MATCH is no longer
2661     // possible.  We parse it as if the region was the same as that for the
2662     // first number, and if EXACT_MATCH is returned, we replace this with
2663     // NSN_MATCH.
2664     string first_number_region;
2665     GetRegionCodeForCountryCode(first_number.country_code(),
2666                                 &first_number_region);
2667     if (first_number_region != RegionCode::GetUnknown()) {
2668       PhoneNumber second_number_with_first_number_region;
2669       Parse(second_number, first_number_region,
2670             &second_number_with_first_number_region);
2671       MatchType match = IsNumberMatch(first_number,
2672                                       second_number_with_first_number_region);
2673       if (match == EXACT_MATCH) {
2674         return NSN_MATCH;
2675       }
2676       return match;
2677     } else {
2678       // If the first number didn't have a valid country calling code, then we
2679       // parse the second number without one as well.
2680       error_type = ParseHelper(second_number, RegionCode::GetUnknown(), false,
2681                                false, &second_number_as_proto);
2682       if (error_type == NO_PARSING_ERROR) {
2683         return IsNumberMatch(first_number, second_number_as_proto);
2684       }
2685     }
2686   }
2687   // One or more of the phone numbers we are trying to match is not a viable
2688   // phone number.
2689   return INVALID_NUMBER;
2690 }
2691
2692 AsYouTypeFormatter* PhoneNumberUtil::GetAsYouTypeFormatter(
2693     const string& region_code) const {
2694   return new AsYouTypeFormatter(region_code);
2695 }
2696
2697 bool PhoneNumberUtil::CanBeInternationallyDialled(
2698     const PhoneNumber& number) const {
2699   string region_code;
2700   GetRegionCodeForNumber(number, &region_code);
2701   const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
2702   if (!metadata) {
2703     // Note numbers belonging to non-geographical entities (e.g. +800 numbers)
2704     // are always internationally diallable, and will be caught here.
2705     return true;
2706   }
2707   string national_significant_number;
2708   GetNationalSignificantNumber(number, &national_significant_number);
2709   return !IsNumberMatchingDesc(
2710       national_significant_number, metadata->no_international_dialling(),
2711       reg_exps_->regexp_cache_.get());
2712 }
2713
2714 }  // namespace phonenumbers
2715 }  // namespace i18n