Add partial C++0x support and recognition of GCC function clone suffixes to
[platform/upstream/glog.git] / src / demangle.cc
1 // Copyright (c) 2006, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 //
30 // Author: Satoru Takabayashi
31 //
32 // For reference check out:
33 // http://www.codesourcery.com/public/cxx-abi/abi.html#mangling
34 //
35 // Note that we only have partial C++0x support yet.
36
37 #include <stdio.h>  // for NULL
38 #include "demangle.h"
39
40 _START_GOOGLE_NAMESPACE_
41
42 typedef struct {
43   const char *abbrev;
44   const char *real_name;
45 } AbbrevPair;
46
47 // List of operators from Itanium C++ ABI.
48 static const AbbrevPair kOperatorList[] = {
49   { "nw", "new" },
50   { "na", "new[]" },
51   { "dl", "delete" },
52   { "da", "delete[]" },
53   { "ps", "+" },
54   { "ng", "-" },
55   { "ad", "&" },
56   { "de", "*" },
57   { "co", "~" },
58   { "pl", "+" },
59   { "mi", "-" },
60   { "ml", "*" },
61   { "dv", "/" },
62   { "rm", "%" },
63   { "an", "&" },
64   { "or", "|" },
65   { "eo", "^" },
66   { "aS", "=" },
67   { "pL", "+=" },
68   { "mI", "-=" },
69   { "mL", "*=" },
70   { "dV", "/=" },
71   { "rM", "%=" },
72   { "aN", "&=" },
73   { "oR", "|=" },
74   { "eO", "^=" },
75   { "ls", "<<" },
76   { "rs", ">>" },
77   { "lS", "<<=" },
78   { "rS", ">>=" },
79   { "eq", "==" },
80   { "ne", "!=" },
81   { "lt", "<" },
82   { "gt", ">" },
83   { "le", "<=" },
84   { "ge", ">=" },
85   { "nt", "!" },
86   { "aa", "&&" },
87   { "oo", "||" },
88   { "pp", "++" },
89   { "mm", "--" },
90   { "cm", "," },
91   { "pm", "->*" },
92   { "pt", "->" },
93   { "cl", "()" },
94   { "ix", "[]" },
95   { "qu", "?" },
96   { "st", "sizeof" },
97   { "sz", "sizeof" },
98   { NULL, NULL },
99 };
100
101 // List of builtin types from Itanium C++ ABI.
102 static const AbbrevPair kBuiltinTypeList[] = {
103   { "v", "void" },
104   { "w", "wchar_t" },
105   { "b", "bool" },
106   { "c", "char" },
107   { "a", "signed char" },
108   { "h", "unsigned char" },
109   { "s", "short" },
110   { "t", "unsigned short" },
111   { "i", "int" },
112   { "j", "unsigned int" },
113   { "l", "long" },
114   { "m", "unsigned long" },
115   { "x", "long long" },
116   { "y", "unsigned long long" },
117   { "n", "__int128" },
118   { "o", "unsigned __int128" },
119   { "f", "float" },
120   { "d", "double" },
121   { "e", "long double" },
122   { "g", "__float128" },
123   { "z", "ellipsis" },
124   { NULL, NULL }
125 };
126
127 // List of substitutions Itanium C++ ABI.
128 static const AbbrevPair kSubstitutionList[] = {
129   { "St", "" },
130   { "Sa", "allocator" },
131   { "Sb", "basic_string" },
132   // std::basic_string<char, std::char_traits<char>,std::allocator<char> >
133   { "Ss", "string"},
134   // std::basic_istream<char, std::char_traits<char> >
135   { "Si", "istream" },
136   // std::basic_ostream<char, std::char_traits<char> >
137   { "So", "ostream" },
138   // std::basic_iostream<char, std::char_traits<char> >
139   { "Sd", "iostream" },
140   { NULL, NULL }
141 };
142
143 // State needed for demangling.
144 typedef struct {
145   const char *mangled_cur;  // Cursor of mangled name.
146   const char *mangled_end;  // End of mangled name.
147   char *out_cur;            // Cursor of output string.
148   const char *out_begin;    // Beginning of output string.
149   const char *out_end;      // End of output string.
150   const char *prev_name;    // For constructors/destructors.
151   int prev_name_length;     // For constructors/destructors.
152   int nest_level;           // For nested names.
153   int number;               // Remember the previous number.
154   bool append;              // Append flag.
155   bool overflowed;          // True if output gets overflowed.
156 } State;
157
158 // We don't use strlen() in libc since it's not guaranteed to be async
159 // signal safe.
160 static size_t StrLen(const char *str) {
161   size_t len = 0;
162   while (*str != '\0') {
163     ++str;
164     ++len;
165   }
166   return len;
167 }
168
169 // Returns true if "str" has "prefix" as a prefix.
170 static bool StrPrefix(const char *str, const char *prefix) {
171   size_t i = 0;
172   while (str[i] != '\0' && prefix[i] != '\0' &&
173          str[i] == prefix[i]) {
174     ++i;
175   }
176   return prefix[i] == '\0';  // Consumed everything in "prefix".
177 }
178
179 static void InitState(State *state, const char *mangled,
180                       char *out, int out_size) {
181   state->mangled_cur = mangled;
182   state->mangled_end = mangled + StrLen(mangled);
183   state->out_cur = out;
184   state->out_begin = out;
185   state->out_end = out + out_size;
186   state->prev_name  = NULL;
187   state->prev_name_length = -1;
188   state->nest_level = -1;
189   state->number = -1;
190   state->append = true;
191   state->overflowed = false;
192 }
193
194 // Calculates the remaining length of the mangled name.
195 static int RemainingLength(State *state) {
196   return state->mangled_end - state->mangled_cur;
197 }
198
199 // Returns true and advances "mangled_cur" if we find "c" at
200 // "mangled_cur" position.
201 static bool ParseChar(State *state, const char c) {
202   if (RemainingLength(state) >= 1 && *state->mangled_cur == c) {
203     ++state->mangled_cur;
204     return true;
205   }
206   return false;
207 }
208
209 // Returns true and advances "mangled_cur" if we find "two_chars" at
210 // "mangled_cur" position.
211 static bool ParseTwoChar(State *state, const char *two_chars) {
212   if (RemainingLength(state) >= 2 &&
213       state->mangled_cur[0] == two_chars[0] &&
214       state->mangled_cur[1] == two_chars[1]) {
215     state->mangled_cur += 2;
216     return true;
217   }
218   return false;
219 }
220
221 // Returns true and advances "mangled_cur" if we find any character in
222 // "char_class" at "mangled_cur" position.
223 static bool ParseCharClass(State *state, const char *char_class) {
224   if (state->mangled_cur == state->mangled_end) {
225     return false;
226   }
227   const char *p = char_class;
228   for (; *p != '\0'; ++p) {
229     if (*state->mangled_cur == *p) {
230       state->mangled_cur += 1;
231       return true;
232     }
233   }
234   return false;
235 }
236
237 // This function is used for handling an optional non-terminal.
238 static bool Optional(bool status) {
239   return true;
240 }
241
242 // This function is used for handling <non-terminal>+ syntax.
243 typedef bool (*ParseFunc)(State *);
244 static bool OneOrMore(ParseFunc parse_func, State *state) {
245   if (parse_func(state)) {
246     while (parse_func(state)) {
247     }
248     return true;
249   }
250   return false;
251 }
252
253 // This function is used for handling <non-terminal>* syntax. The function
254 // always returns true and must be followed by a termination symbol or a
255 // terminating sequence not handled by parse_func (e.g. ParseChar(state, 'E')).
256 static bool ZeroOrMore(ParseFunc parse_func, State *state) {
257   while (parse_func(state)) {
258   }
259   return true;
260 }
261
262 // Append "str" at "out_cur".  If there is an overflow, "overflowed"
263 // is set to true for later use.  The output string is ensured to
264 // always terminate with '\0' as long as there is no overflow.
265 static void Append(State *state, const char * const str, const int length) {
266   int i;
267   for (i = 0; i < length; ++i) {
268     if (state->out_cur + 1 < state->out_end) {  // +1 for '\0'
269       *state->out_cur = str[i];
270       ++state->out_cur;
271     } else {
272       state->overflowed = true;
273       break;
274     }
275   }
276   if (!state->overflowed) {
277     *state->out_cur = '\0';  // Terminate it with '\0'
278   }
279 }
280
281 // We don't use equivalents in libc to avoid locale issues.
282 static bool IsLower(char c) {
283   return c >= 'a' && c <= 'z';
284 }
285
286 static bool IsAlpha(char c) {
287   return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
288 }
289
290 static bool IsDigit(char c) {
291   return c >= '0' && c <= '9';
292 }
293
294 // Returns true if "str" is a function clone suffix.  These suffixes are used
295 // by GCC 4.5.x and later versions to indicate functions which have been
296 // cloned during optimization.  We treat any sequence (.<alpha>+.<digit>+)+ as
297 // a function clone suffix.
298 static bool IsFunctionCloneSuffix(const char *str) {
299   size_t i = 0;
300   while (str[i] != '\0') {
301     // Consume a single .<alpha>+.<digit>+ sequence.
302     if (str[i] != '.' || !IsAlpha(str[i + 1])) {
303       return false;
304     }
305     i += 2;
306     while (IsAlpha(str[i])) {
307       ++i;
308     }
309     if (str[i] != '.' || !IsDigit(str[i + 1])) {
310       return false;
311     }
312     i += 2;
313     while (IsDigit(str[i])) {
314       ++i;
315     }
316   }
317   return true;  // Consumed everything in "str".
318 }
319
320 // Append "str" with some tweaks, iff "append" state is true.
321 // Returns true so that it can be placed in "if" conditions.
322 static void MaybeAppendWithLength(State *state, const char * const str,
323                                   const int length) {
324   if (state->append && length > 0) {
325     // Append a space if the output buffer ends with '<' and "str"
326     // starts with '<' to avoid <<<.
327     if (str[0] == '<' && state->out_begin < state->out_cur  &&
328         state->out_cur[-1] == '<') {
329       Append(state, " ", 1);
330     }
331     // Remember the last identifier name for ctors/dtors.
332     if (IsAlpha(str[0]) || str[0] == '_') {
333       state->prev_name = state->out_cur;
334       state->prev_name_length = length;
335     }
336     Append(state, str, length);
337   }
338 }
339
340 // A convenient wrapper arount MaybeAppendWithLength().
341 static bool MaybeAppend(State *state, const char * const str) {
342   if (state->append) {
343     int length = StrLen(str);
344     MaybeAppendWithLength(state, str, length);
345   }
346   return true;
347 }
348
349 // This function is used for handling nested names.
350 static bool EnterNestedName(State *state) {
351   state->nest_level = 0;
352   return true;
353 }
354
355 // This function is used for handling nested names.
356 static bool LeaveNestedName(State *state, int prev_value) {
357   state->nest_level = prev_value;
358   return true;
359 }
360
361 // Disable the append mode not to print function parameters, etc.
362 static bool DisableAppend(State *state) {
363   state->append = false;
364   return true;
365 }
366
367 // Restore the append mode to the previous state.
368 static bool RestoreAppend(State *state, bool prev_value) {
369   state->append = prev_value;
370   return true;
371 }
372
373 // Increase the nest level for nested names.
374 static void MaybeIncreaseNestLevel(State *state) {
375   if (state->nest_level > -1) {
376     ++state->nest_level;
377   }
378 }
379
380 // Appends :: for nested names if necessary.
381 static void MaybeAppendSeparator(State *state) {
382   if (state->nest_level >= 1) {
383     MaybeAppend(state, "::");
384   }
385 }
386
387 // Cancel the last separator if necessary.
388 static void MaybeCancelLastSeparator(State *state) {
389   if (state->nest_level >= 1 && state->append &&
390       state->out_begin <= state->out_cur - 2) {
391     state->out_cur -= 2;
392     *state->out_cur = '\0';
393   }
394 }
395
396 // Returns true if identifier pointed by "mangled_cur" is anonymous
397 // namespace.
398 static bool IdentifierIsAnonymousNamespace(State *state) {
399   const char anon_prefix[] = "_GLOBAL__N_";
400   return (state->number > sizeof(anon_prefix) - 1 &&  // Should be longer.
401           StrPrefix(state->mangled_cur, anon_prefix));
402 }
403
404 // Forward declarations of our parsing functions.
405 static bool ParseMangledName(State *state);
406 static bool ParseEncoding(State *state);
407 static bool ParseName(State *state);
408 static bool ParseUnscopedName(State *state);
409 static bool ParseUnscopedTemplateName(State *state);
410 static bool ParseNestedName(State *state);
411 static bool ParsePrefix(State *state);
412 static bool ParseUnqualifiedName(State *state);
413 static bool ParseSourceName(State *state);
414 static bool ParseLocalSourceName(State *state);
415 static bool ParseNumber(State *state);
416 static bool ParseFloatNumber(State *state);
417 static bool ParseSeqId(State *state);
418 static bool ParseIdentifier(State *state);
419 static bool ParseOperatorName(State *state);
420 static bool ParseSpecialName(State *state);
421 static bool ParseCallOffset(State *state);
422 static bool ParseNVOffset(State *state);
423 static bool ParseVOffset(State *state);
424 static bool ParseCtorDtorName(State *state);
425 static bool ParseType(State *state);
426 static bool ParseCVQualifiers(State *state);
427 static bool ParseBuiltinType(State *state);
428 static bool ParseFunctionType(State *state);
429 static bool ParseBareFunctionType(State *state);
430 static bool ParseClassEnumType(State *state);
431 static bool ParseArrayType(State *state);
432 static bool ParsePointerToMemberType(State *state);
433 static bool ParseTemplateParam(State *state);
434 static bool ParseTemplateTemplateParam(State *state);
435 static bool ParseTemplateArgs(State *state);
436 static bool ParseTemplateArg(State *state);
437 static bool ParseExpression(State *state);
438 static bool ParseExprPrimary(State *state);
439 static bool ParseLocalName(State *state);
440 static bool ParseDiscriminator(State *state);
441 static bool ParseSubstitution(State *state);
442
443 // Implementation note: the following code is a straightforward
444 // translation of the Itanium C++ ABI defined in BNF with a couple of
445 // exceptions.
446 //
447 // - Support GNU extensions not defined in the Itanium C++ ABI
448 // - <prefix> and <template-prefix> are combined to avoid infinite loop
449 // - Reorder patterns to shorten the code
450 // - Reorder patterns to give greedier functions precedence
451 //   We'll mark "Less greedy than" for these cases in the code
452 //
453 // Each parsing function changes the state and returns true on
454 // success.  Otherwise, don't change the state and returns false.  To
455 // ensure that the state isn't changed in the latter case, we save the
456 // original state before we call more than one parsing functions
457 // consecutively with &&, and restore the state if unsuccessful.  See
458 // ParseEncoding() as an example of this convention.  We follow the
459 // convention throughout the code.
460 //
461 // Originally we tried to do demangling without following the full ABI
462 // syntax but it turned out we needed to follow the full syntax to
463 // parse complicated cases like nested template arguments.  Note that
464 // implementing a full-fledged demangler isn't trivial (libiberty's
465 // cp-demangle.c has +4300 lines).
466 //
467 // Note that (foo) in <(foo) ...> is a modifier to be ignored.
468 //
469 // Reference:
470 // - Itanium C++ ABI
471 //   <http://www.codesourcery.com/cxx-abi/abi.html#mangling>
472
473 // <mangled-name> ::= _Z <encoding>
474 static bool ParseMangledName(State *state) {
475   if (ParseTwoChar(state, "_Z") && ParseEncoding(state)) {
476     // Drop trailing function clone suffix, if any.
477     if (IsFunctionCloneSuffix(state->mangled_cur)) {
478       state->mangled_cur = state->mangled_end;
479     }
480     // Append trailing version suffix if any.
481     // ex. _Z3foo@@GLIBCXX_3.4
482     if (state->mangled_cur < state->mangled_end &&
483         state->mangled_cur[0] == '@') {
484       MaybeAppend(state, state->mangled_cur);
485       state->mangled_cur = state->mangled_end;
486     }
487     return true;
488   }
489   return false;
490 }
491
492 // <encoding> ::= <(function) name> <bare-function-type>
493 //            ::= <(data) name>
494 //            ::= <special-name>
495 static bool ParseEncoding(State *state) {
496   State copy = *state;
497   if (ParseName(state) && ParseBareFunctionType(state)) {
498     return true;
499   }
500   *state = copy;
501
502   if (ParseName(state) || ParseSpecialName(state)) {
503     return true;
504   }
505   return false;
506 }
507
508 // <name> ::= <nested-name>
509 //        ::= <unscoped-template-name> <template-args>
510 //        ::= <unscoped-name>
511 //        ::= <local-name>
512 static bool ParseName(State *state) {
513   if (ParseNestedName(state) || ParseLocalName(state)) {
514     return true;
515   }
516
517   State copy = *state;
518   if (ParseUnscopedTemplateName(state) &&
519       ParseTemplateArgs(state)) {
520     return true;
521   }
522   *state = copy;
523
524   // Less greedy than <unscoped-template-name> <template-args>.
525   if (ParseUnscopedName(state)) {
526     return true;
527   }
528   return false;
529 }
530
531 // <unscoped-name> ::= <unqualified-name>
532 //                 ::= St <unqualified-name>
533 static bool ParseUnscopedName(State *state) {
534   if (ParseUnqualifiedName(state)) {
535     return true;
536   }
537
538   State copy = *state;
539   if (ParseTwoChar(state, "St") &&
540       MaybeAppend(state, "std::") &&
541       ParseUnqualifiedName(state)) {
542     return true;
543   }
544   *state = copy;
545   return false;
546 }
547
548 // <unscoped-template-name> ::= <unscoped-name>
549 //                          ::= <substitution>
550 static bool ParseUnscopedTemplateName(State *state) {
551   return ParseUnscopedName(state) || ParseSubstitution(state);
552 }
553
554 // <nested-name> ::= N [<CV-qualifiers>] <prefix> <unqualified-name> E
555 //               ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
556 static bool ParseNestedName(State *state) {
557   State copy = *state;
558   if (ParseChar(state, 'N') &&
559       EnterNestedName(state) &&
560       Optional(ParseCVQualifiers(state)) &&
561       ParsePrefix(state) &&
562       LeaveNestedName(state, copy.nest_level) &&
563       ParseChar(state, 'E')) {
564     return true;
565   }
566   *state = copy;
567   return false;
568 }
569
570 // This part is tricky.  If we literally translate them to code, we'll
571 // end up infinite loop.  Hence we merge them to avoid the case.
572 //
573 // <prefix> ::= <prefix> <unqualified-name>
574 //          ::= <template-prefix> <template-args>
575 //          ::= <template-param>
576 //          ::= <substitution>
577 //          ::= # empty
578 // <template-prefix> ::= <prefix> <(template) unqualified-name>
579 //                   ::= <template-param>
580 //                   ::= <substitution>
581 static bool ParsePrefix(State *state) {
582   bool has_something = false;
583   while (true) {
584     MaybeAppendSeparator(state);
585     if (ParseTemplateParam(state) ||
586         ParseSubstitution(state) ||
587         ParseUnscopedName(state)) {
588       has_something = true;
589       MaybeIncreaseNestLevel(state);
590       continue;
591     }
592     MaybeCancelLastSeparator(state);
593     if (has_something && ParseTemplateArgs(state)) {
594       return ParsePrefix(state);
595     } else {
596       break;
597     }
598   }
599   return true;
600 }
601
602 // <unqualified-name> ::= <operator-name>
603 //                    ::= <ctor-dtor-name>
604 //                    ::= <source-name>
605 //                    ::= <local-source-name>
606 static bool ParseUnqualifiedName(State *state) {
607   return (ParseOperatorName(state) ||
608           ParseCtorDtorName(state) ||
609           ParseSourceName(state) ||
610           ParseLocalSourceName(state));
611 }
612
613 // <source-name> ::= <positive length number> <identifier>
614 static bool ParseSourceName(State *state) {
615   State copy = *state;
616   if (ParseNumber(state) && ParseIdentifier(state)) {
617     return true;
618   }
619   *state = copy;
620   return false;
621 }
622
623 // <local-source-name> ::= L <source-name> [<discriminator>]
624 //
625 // References:
626 //   http://gcc.gnu.org/bugzilla/show_bug.cgi?id=31775
627 //   http://gcc.gnu.org/viewcvs?view=rev&revision=124467
628 static bool ParseLocalSourceName(State *state) {
629   State copy = *state;
630   if (ParseChar(state, 'L') && ParseSourceName(state) &&
631       Optional(ParseDiscriminator(state))) {
632     return true;
633   }
634   *state = copy;
635   return false;
636 }
637
638 // <number> ::= [n] <non-negative decimal integer>
639 static bool ParseNumber(State *state) {
640   int sign = 1;
641   if (ParseChar(state, 'n')) {
642     sign = -1;
643   }
644   const char *p = state->mangled_cur;
645   int number = 0;
646   for (;p < state->mangled_end; ++p) {
647     if (IsDigit(*p)) {
648       number = number * 10 + (*p - '0');
649     } else {
650       break;
651     }
652   }
653   if (p != state->mangled_cur) {  // Conversion succeeded.
654     state->mangled_cur = p;
655     state->number = number * sign;
656     return true;
657   }
658   return false;
659 }
660
661 // Floating-point literals are encoded using a fixed-length lowercase
662 // hexadecimal string.
663 static bool ParseFloatNumber(State *state) {
664   const char *p = state->mangled_cur;
665   int number = 0;
666   for (;p < state->mangled_end; ++p) {
667     if (IsDigit(*p)) {
668       number = number * 16 + (*p - '0');
669     } else if (*p >= 'a' && *p <= 'f') {
670       number = number * 16 + (*p - 'a' + 10);
671     } else {
672       break;
673     }
674   }
675   if (p != state->mangled_cur) {  // Conversion succeeded.
676     state->mangled_cur = p;
677     state->number = number;
678     return true;
679   }
680   return false;
681 }
682
683 // The <seq-id> is a sequence number in base 36,
684 // using digits and upper case letters
685 static bool ParseSeqId(State *state) {
686   const char *p = state->mangled_cur;
687   int number = 0;
688   for (;p < state->mangled_end; ++p) {
689     if (IsDigit(*p)) {
690       number = number * 36 + (*p - '0');
691     } else if (*p >= 'A' && *p <= 'Z') {
692       number = number * 36 + (*p - 'A' + 10);
693     } else {
694       break;
695     }
696   }
697   if (p != state->mangled_cur) {  // Conversion succeeded.
698     state->mangled_cur = p;
699     state->number = number;
700     return true;
701   }
702   return false;
703 }
704
705 // <identifier> ::= <unqualified source code identifier>
706 static bool ParseIdentifier(State *state) {
707   if (state->number == -1 ||
708       RemainingLength(state) < state->number) {
709     return false;
710   }
711   if (IdentifierIsAnonymousNamespace(state)) {
712     MaybeAppend(state, "(anonymous namespace)");
713   } else {
714     MaybeAppendWithLength(state, state->mangled_cur, state->number);
715   }
716   state->mangled_cur += state->number;
717   state->number = -1;  // Reset the number.
718   return true;
719 }
720
721 // <operator-name> ::= nw, and other two letters cases
722 //                 ::= cv <type>  # (cast)
723 //                 ::= v  <digit> <source-name> # vendor extended operator
724 static bool ParseOperatorName(State *state) {
725   if (RemainingLength(state) < 2) {
726     return false;
727   }
728   // First check with "cv" (cast) case.
729   State copy = *state;
730   if (ParseTwoChar(state, "cv") &&
731       MaybeAppend(state, "operator ") &&
732       EnterNestedName(state) &&
733       ParseType(state) &&
734       LeaveNestedName(state, copy.nest_level)) {
735     return true;
736   }
737   *state = copy;
738
739   // Then vendor extended operators.
740   if (ParseChar(state, 'v') && ParseCharClass(state, "0123456789") &&
741       ParseSourceName(state)) {
742     return true;
743   }
744   *state = copy;
745
746   // Other operator names should start with a lower alphabet followed
747   // by a lower/upper alphabet.
748   if (!(IsLower(state->mangled_cur[0]) &&
749         IsAlpha(state->mangled_cur[1]))) {
750     return false;
751   }
752   // We may want to perform a binary search if we really need speed.
753   const AbbrevPair *p;
754   for (p = kOperatorList; p->abbrev != NULL; ++p) {
755     if (state->mangled_cur[0] == p->abbrev[0] &&
756         state->mangled_cur[1] == p->abbrev[1]) {
757       MaybeAppend(state, "operator");
758       if (IsLower(*p->real_name)) {  // new, delete, etc.
759         MaybeAppend(state, " ");
760       }
761       MaybeAppend(state, p->real_name);
762       state->mangled_cur += 2;
763       return true;
764     }
765   }
766   return false;
767 }
768
769 // <special-name> ::= TV <type>
770 //                ::= TT <type>
771 //                ::= TI <type>
772 //                ::= TS <type>
773 //                ::= Tc <call-offset> <call-offset> <(base) encoding>
774 //                ::= GV <(object) name>
775 //                ::= T <call-offset> <(base) encoding>
776 // G++ extensions:
777 //                ::= TC <type> <(offset) number> _ <(base) type>
778 //                ::= TF <type>
779 //                ::= TJ <type>
780 //                ::= GR <name>
781 //                ::= GA <encoding>
782 //                ::= Th <call-offset> <(base) encoding>
783 //                ::= Tv <call-offset> <(base) encoding>
784 //
785 // Note: we don't care much about them since they don't appear in
786 // stack traces.  The are special data.
787 static bool ParseSpecialName(State *state) {
788   State copy = *state;
789   if (ParseChar(state, 'T') &&
790       ParseCharClass(state, "VTIS") &&
791       ParseType(state)) {
792     return true;
793   }
794   *state = copy;
795
796   if (ParseTwoChar(state, "Tc") && ParseCallOffset(state) &&
797       ParseCallOffset(state) && ParseEncoding(state)) {
798     return true;
799   }
800   *state = copy;
801
802   if (ParseTwoChar(state, "GV") &&
803       ParseName(state)) {
804     return true;
805   }
806   *state = copy;
807
808   if (ParseChar(state, 'T') && ParseCallOffset(state) &&
809       ParseEncoding(state)) {
810     return true;
811   }
812   *state = copy;
813
814   // G++ extensions
815   if (ParseTwoChar(state, "TC") && ParseType(state) &&
816       ParseNumber(state) && ParseChar(state, '_') &&
817       DisableAppend(state) &&
818       ParseType(state)) {
819     RestoreAppend(state, copy.append);
820     return true;
821   }
822   *state = copy;
823
824   if (ParseChar(state, 'T') && ParseCharClass(state, "FJ") &&
825       ParseType(state)) {
826     return true;
827   }
828   *state = copy;
829
830   if (ParseTwoChar(state, "GR") && ParseName(state)) {
831     return true;
832   }
833   *state = copy;
834
835   if (ParseTwoChar(state, "GA") && ParseEncoding(state)) {
836     return true;
837   }
838   *state = copy;
839
840   if (ParseChar(state, 'T') && ParseCharClass(state, "hv") &&
841       ParseCallOffset(state) && ParseEncoding(state)) {
842     return true;
843   }
844   *state = copy;
845   return false;
846 }
847
848 // <call-offset> ::= h <nv-offset> _
849 //               ::= v <v-offset> _
850 static bool ParseCallOffset(State *state) {
851   State copy = *state;
852   if (ParseChar(state, 'h') &&
853       ParseNVOffset(state) && ParseChar(state, '_')) {
854     return true;
855   }
856   *state = copy;
857
858   if (ParseChar(state, 'v') &&
859       ParseVOffset(state) && ParseChar(state, '_')) {
860     return true;
861   }
862   *state = copy;
863
864   return false;
865 }
866
867 // <nv-offset> ::= <(offset) number>
868 static bool ParseNVOffset(State *state) {
869   return ParseNumber(state);
870 }
871
872 // <v-offset>  ::= <(offset) number> _ <(virtual offset) number>
873 static bool ParseVOffset(State *state) {
874   State copy = *state;
875   if (ParseNumber(state) && ParseChar(state, '_') &&
876       ParseNumber(state)) {
877     return true;
878   }
879   *state = copy;
880   return false;
881 }
882
883 // <ctor-dtor-name> ::= C1 | C2 | C3
884 //                  ::= D0 | D1 | D2
885 static bool ParseCtorDtorName(State *state) {
886   State copy = *state;
887   if (ParseChar(state, 'C') &&
888       ParseCharClass(state, "123")) {
889     const char * const prev_name = state->prev_name;
890     const int prev_name_length = state->prev_name_length;
891     MaybeAppendWithLength(state, prev_name, prev_name_length);
892     return true;
893   }
894   *state = copy;
895
896   if (ParseChar(state, 'D') &&
897       ParseCharClass(state, "012")) {
898     const char * const prev_name = state->prev_name;
899     const int prev_name_length = state->prev_name_length;
900     MaybeAppend(state, "~");
901     MaybeAppendWithLength(state, prev_name, prev_name_length);
902     return true;
903   }
904   *state = copy;
905   return false;
906 }
907
908 // <type> ::= <CV-qualifiers> <type>
909 //        ::= P <type>   # pointer-to
910 //        ::= R <type>   # reference-to
911 //        ::= O <type>   # rvalue reference-to (C++0x)
912 //        ::= C <type>   # complex pair (C 2000)
913 //        ::= G <type>   # imaginary (C 2000)
914 //        ::= U <source-name> <type>  # vendor extended type qualifier
915 //        ::= <builtin-type>
916 //        ::= <function-type>
917 //        ::= <class-enum-type>
918 //        ::= <array-type>
919 //        ::= <pointer-to-member-type>
920 //        ::= <template-template-param> <template-args>
921 //        ::= <template-param>
922 //        ::= <substitution>
923 //        ::= Dp <type>          # pack expansion of (C++0x)
924 //        ::= Dt <expression> E  # decltype of an id-expression or class
925 //                               # member access (C++0x)
926 //        ::= DT <expression> E  # decltype of an expression (C++0x)
927 //
928 static bool ParseType(State *state) {
929   // We should check CV-qualifers, and PRGC things first.
930   State copy = *state;
931   if (ParseCVQualifiers(state) && ParseType(state)) {
932     return true;
933   }
934   *state = copy;
935
936   if (ParseCharClass(state, "OPRCG") && ParseType(state)) {
937     return true;
938   }
939   *state = copy;
940
941   if (ParseTwoChar(state, "Dp") && ParseType(state)) {
942     return true;
943   }
944   *state = copy;
945
946   if (ParseChar(state, 'D') && ParseCharClass(state, "tT") &&
947       ParseExpression(state) && ParseChar(state, 'E')) {
948     return true;
949   }
950   *state = copy;
951
952   if (ParseChar(state, 'U') && ParseSourceName(state) &&
953       ParseType(state)) {
954     return true;
955   }
956   *state = copy;
957
958   if (ParseBuiltinType(state) ||
959       ParseFunctionType(state) ||
960       ParseClassEnumType(state) ||
961       ParseArrayType(state) ||
962       ParsePointerToMemberType(state) ||
963       ParseSubstitution(state)) {
964     return true;
965   }
966
967   if (ParseTemplateTemplateParam(state) &&
968       ParseTemplateArgs(state)) {
969     return true;
970   }
971   *state = copy;
972
973   // Less greedy than <template-template-param> <template-args>.
974   if (ParseTemplateParam(state)) {
975     return true;
976   }
977
978   return false;
979 }
980
981 // <CV-qualifiers> ::= [r] [V] [K]
982 // We don't allow empty <CV-qualifiers> to avoid infinite loop in
983 // ParseType().
984 static bool ParseCVQualifiers(State *state) {
985   int num_cv_qualifiers = 0;
986   num_cv_qualifiers += ParseChar(state, 'r');
987   num_cv_qualifiers += ParseChar(state, 'V');
988   num_cv_qualifiers += ParseChar(state, 'K');
989   return num_cv_qualifiers > 0;
990 }
991
992 // <builtin-type> ::= v, etc.
993 //                ::= u <source-name>
994 static bool ParseBuiltinType(State *state) {
995   const AbbrevPair *p;
996   for (p = kBuiltinTypeList; p->abbrev != NULL; ++p) {
997     if (state->mangled_cur[0] == p->abbrev[0]) {
998       MaybeAppend(state, p->real_name);
999       ++state->mangled_cur;
1000       return true;
1001     }
1002   }
1003
1004   State copy = *state;
1005   if (ParseChar(state, 'u') && ParseSourceName(state)) {
1006     return true;
1007   }
1008   *state = copy;
1009   return false;
1010 }
1011
1012 // <function-type> ::= F [Y] <bare-function-type> E
1013 static bool ParseFunctionType(State *state) {
1014   State copy = *state;
1015   if (ParseChar(state, 'F') && Optional(ParseChar(state, 'Y')) &&
1016       ParseBareFunctionType(state) && ParseChar(state, 'E')) {
1017     return true;
1018   }
1019   *state = copy;
1020   return false;
1021 }
1022
1023 // <bare-function-type> ::= <(signature) type>+
1024 static bool ParseBareFunctionType(State *state) {
1025   State copy = *state;
1026   DisableAppend(state);
1027   if (OneOrMore(ParseType, state)) {
1028     RestoreAppend(state, copy.append);
1029     MaybeAppend(state, "()");
1030     return true;
1031   }
1032   *state = copy;
1033   return false;
1034 }
1035
1036 // <class-enum-type> ::= <name>
1037 static bool ParseClassEnumType(State *state) {
1038   return ParseName(state);
1039 }
1040
1041 // <array-type> ::= A <(positive dimension) number> _ <(element) type>
1042 //              ::= A [<(dimension) expression>] _ <(element) type>
1043 static bool ParseArrayType(State *state) {
1044   State copy = *state;
1045   if (ParseChar(state, 'A') && ParseNumber(state) &&
1046       ParseChar(state, '_') && ParseType(state)) {
1047     return true;
1048   }
1049   *state = copy;
1050
1051   if (ParseChar(state, 'A') && Optional(ParseExpression(state)) &&
1052       ParseChar(state, '_') && ParseType(state)) {
1053     return true;
1054   }
1055   *state = copy;
1056   return false;
1057 }
1058
1059 // <pointer-to-member-type> ::= M <(class) type> <(member) type>
1060 static bool ParsePointerToMemberType(State *state) {
1061   State copy = *state;
1062   if (ParseChar(state, 'M') && ParseType(state) &&
1063       ParseType(state)) {
1064     return true;
1065   }
1066   *state = copy;
1067   return false;
1068 }
1069
1070 // <template-param> ::= T_
1071 //                  ::= T <parameter-2 non-negative number> _
1072 static bool ParseTemplateParam(State *state) {
1073   if (ParseTwoChar(state, "T_")) {
1074     MaybeAppend(state, "?");  // We don't support template substitutions.
1075     return true;
1076   }
1077
1078   State copy = *state;
1079   if (ParseChar(state, 'T') && ParseNumber(state) &&
1080       ParseChar(state, '_')) {
1081     MaybeAppend(state, "?");  // We don't support template substitutions.
1082     return true;
1083   }
1084   *state = copy;
1085   return false;
1086 }
1087
1088
1089 // <template-template-param> ::= <template-param>
1090 //                           ::= <substitution>
1091 static bool ParseTemplateTemplateParam(State *state) {
1092   return (ParseTemplateParam(state) ||
1093           ParseSubstitution(state));
1094 }
1095
1096 // <template-args> ::= I <template-arg>+ E
1097 static bool ParseTemplateArgs(State *state) {
1098   State copy = *state;
1099   DisableAppend(state);
1100   if (ParseChar(state, 'I') &&
1101       OneOrMore(ParseTemplateArg, state) &&
1102       ParseChar(state, 'E')) {
1103     RestoreAppend(state, copy.append);
1104     MaybeAppend(state, "<>");
1105     return true;
1106   }
1107   *state = copy;
1108   return false;
1109 }
1110
1111 // <template-arg>  ::= <type>
1112 //                 ::= <expr-primary>
1113 //                 ::= I <template-arg>* E        # argument pack
1114 //                 ::= X <expression> E
1115 static bool ParseTemplateArg(State *state) {
1116   State copy = *state;
1117   if (ParseChar(state, 'I') &&
1118       ZeroOrMore(ParseTemplateArg, state) &&
1119       ParseChar(state, 'E')) {
1120     return true;
1121   }
1122   *state = copy;
1123
1124   if (ParseType(state) ||
1125       ParseExprPrimary(state)) {
1126     return true;
1127   }
1128   *state = copy;
1129
1130   if (ParseChar(state, 'X') && ParseExpression(state) &&
1131       ParseChar(state, 'E')) {
1132     return true;
1133   }
1134   *state = copy;
1135   return false;
1136 }
1137
1138 // <expression> ::= <template-param>
1139 //              ::= <expr-primary>
1140 //              ::= <unary operator-name> <expression>
1141 //              ::= <binary operator-name> <expression> <expression>
1142 //              ::= <trinary operator-name> <expression> <expression>
1143 //                  <expression>
1144 //              ::= st <type>
1145 //              ::= sr <type> <unqualified-name> <template-args>
1146 //              ::= sr <type> <unqualified-name>
1147 static bool ParseExpression(State *state) {
1148   if (ParseTemplateParam(state) || ParseExprPrimary(state)) {
1149     return true;
1150   }
1151
1152   State copy = *state;
1153   if (ParseOperatorName(state) &&
1154       ParseExpression(state) &&
1155       ParseExpression(state) &&
1156       ParseExpression(state)) {
1157     return true;
1158   }
1159   *state = copy;
1160
1161   if (ParseOperatorName(state) &&
1162       ParseExpression(state) &&
1163       ParseExpression(state)) {
1164     return true;
1165   }
1166   *state = copy;
1167
1168   if (ParseOperatorName(state) &&
1169       ParseExpression(state)) {
1170     return true;
1171   }
1172   *state = copy;
1173
1174   if (ParseTwoChar(state, "st") && ParseType(state)) {
1175     return true;
1176   }
1177   *state = copy;
1178
1179   if (ParseTwoChar(state, "sr") && ParseType(state) &&
1180       ParseUnqualifiedName(state) &&
1181       ParseTemplateArgs(state)) {
1182     return true;
1183   }
1184   *state = copy;
1185
1186   if (ParseTwoChar(state, "sr") && ParseType(state) &&
1187       ParseUnqualifiedName(state)) {
1188     return true;
1189   }
1190   *state = copy;
1191   return false;
1192 }
1193
1194 // <expr-primary> ::= L <type> <(value) number> E
1195 //                ::= L <type> <(value) float> E
1196 //                ::= L <mangled-name> E
1197 //                // A bug in g++'s C++ ABI version 2 (-fabi-version=2).
1198 //                ::= LZ <encoding> E
1199 static bool ParseExprPrimary(State *state) {
1200   State copy = *state;
1201   if (ParseChar(state, 'L') && ParseType(state) &&
1202       ParseNumber(state) &&
1203       ParseChar(state, 'E')) {
1204     return true;
1205   }
1206   *state = copy;
1207
1208   if (ParseChar(state, 'L') && ParseType(state) &&
1209       ParseFloatNumber(state) &&
1210       ParseChar(state, 'E')) {
1211     return true;
1212   }
1213   *state = copy;
1214
1215   if (ParseChar(state, 'L') && ParseMangledName(state) &&
1216       ParseChar(state, 'E')) {
1217     return true;
1218   }
1219   *state = copy;
1220
1221   if (ParseTwoChar(state, "LZ") && ParseEncoding(state) &&
1222       ParseChar(state, 'E')) {
1223     return true;
1224   }
1225   *state = copy;
1226
1227   return false;
1228 }
1229
1230 // <local-name> := Z <(function) encoding> E <(entity) name>
1231 //                 [<discriminator>]
1232 //              := Z <(function) encoding> E s [<discriminator>]
1233 static bool ParseLocalName(State *state) {
1234   State copy = *state;
1235   if (ParseChar(state, 'Z') && ParseEncoding(state) &&
1236       ParseChar(state, 'E') && MaybeAppend(state, "::") &&
1237       ParseName(state) && Optional(ParseDiscriminator(state))) {
1238     return true;
1239   }
1240   *state = copy;
1241
1242   if (ParseChar(state, 'Z') && ParseEncoding(state) &&
1243       ParseTwoChar(state, "Es") && Optional(ParseDiscriminator(state))) {
1244     return true;
1245   }
1246   *state = copy;
1247   return false;
1248 }
1249
1250 // <discriminator> := _ <(non-negative) number>
1251 static bool ParseDiscriminator(State *state) {
1252   State copy = *state;
1253   if (ParseChar(state, '_') && ParseNumber(state)) {
1254     return true;
1255   }
1256   *state = copy;
1257   return false;
1258 }
1259
1260 // <substitution> ::= S_
1261 //                ::= S <seq-id> _
1262 //                ::= St, etc.
1263 static bool ParseSubstitution(State *state) {
1264   if (ParseTwoChar(state, "S_")) {
1265     MaybeAppend(state, "?");  // We don't support substitutions.
1266     return true;
1267   }
1268
1269   State copy = *state;
1270   if (ParseChar(state, 'S') && ParseSeqId(state) &&
1271       ParseChar(state, '_')) {
1272     MaybeAppend(state, "?");  // We don't support substitutions.
1273     return true;
1274   }
1275   *state = copy;
1276
1277   // Expand abbreviations like "St" => "std".
1278   if (ParseChar(state, 'S')) {
1279     const AbbrevPair *p;
1280     for (p = kSubstitutionList; p->abbrev != NULL; ++p) {
1281       if (state->mangled_cur[0] == p->abbrev[1]) {
1282         MaybeAppend(state, "std");
1283         if (p->real_name[0] != '\0') {
1284           MaybeAppend(state, "::");
1285           MaybeAppend(state, p->real_name);
1286         }
1287         state->mangled_cur += 1;
1288         return true;
1289       }
1290     }
1291   }
1292   *state = copy;
1293   return false;
1294 }
1295
1296 // The demangler entry point.
1297 bool Demangle(const char *mangled, char *out, int out_size) {
1298   State state;
1299   InitState(&state, mangled, out, out_size);
1300   return (ParseMangledName(&state) &&
1301           state.overflowed == false &&
1302           RemainingLength(&state) == 0);
1303 }
1304
1305 _END_GOOGLE_NAMESPACE_