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