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