OSDN Git Service

* configure.ac (powerpc*-*-darwin*): #include <sys/cdefs.h>.
[pf3gnuchains/gcc-fork.git] / libiberty / cp-demangle.c
1 /* Demangler for g++ V3 ABI.
2    Copyright (C) 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
3    Written by Ian Lance Taylor <ian@wasabisystems.com>.
4
5    This file is part of the libiberty library, which is part of GCC.
6
7    This file is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    In addition to the permissions in the GNU General Public License, the
13    Free Software Foundation gives you unlimited permission to link the
14    compiled version of this file into combinations with other programs,
15    and to distribute those combinations without any restriction coming
16    from the use of this file.  (The General Public License restrictions
17    do apply in other respects; for example, they cover modification of
18    the file, and distribution when not linked into a combined
19    executable.)
20
21    This program is distributed in the hope that it will be useful,
22    but WITHOUT ANY WARRANTY; without even the implied warranty of
23    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24    GNU General Public License for more details.
25
26    You should have received a copy of the GNU General Public License
27    along with this program; if not, write to the Free Software
28    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. 
29 */
30
31 /* This code implements a demangler for the g++ V3 ABI.  The ABI is
32    described on this web page:
33        http://www.codesourcery.com/cxx-abi/abi.html#mangling
34
35    This code was written while looking at the demangler written by
36    Alex Samuel <samuel@codesourcery.com>.
37
38    This code first pulls the mangled name apart into a list of
39    components, and then walks the list generating the demangled
40    name.
41
42    This file will normally define the following functions, q.v.:
43       char *cplus_demangle_v3(const char *mangled, int options)
44       char *java_demangle_v3(const char *mangled)
45       int cplus_demangle_v3_callback(const char *mangled, int options,
46                                      demangle_callbackref callback)
47       int java_demangle_v3_callback(const char *mangled,
48                                     demangle_callbackref callback)
49       enum gnu_v3_ctor_kinds is_gnu_v3_mangled_ctor (const char *name)
50       enum gnu_v3_dtor_kinds is_gnu_v3_mangled_dtor (const char *name)
51
52    Also, the interface to the component list is public, and defined in
53    demangle.h.  The interface consists of these types, which are
54    defined in demangle.h:
55       enum demangle_component_type
56       struct demangle_component
57       demangle_callbackref
58    and these functions defined in this file:
59       cplus_demangle_fill_name
60       cplus_demangle_fill_extended_operator
61       cplus_demangle_fill_ctor
62       cplus_demangle_fill_dtor
63       cplus_demangle_print
64       cplus_demangle_print_callback
65    and other functions defined in the file cp-demint.c.
66
67    This file also defines some other functions and variables which are
68    only to be used by the file cp-demint.c.
69
70    Preprocessor macros you can define while compiling this file:
71
72    IN_LIBGCC2
73       If defined, this file defines the following functions, q.v.:
74          char *__cxa_demangle (const char *mangled, char *buf, size_t *len,
75                                int *status)
76          int __gcclibcxx_demangle_callback (const char *,
77                                             void (*)
78                                               (const char *, size_t, void *),
79                                             void *)
80       instead of cplus_demangle_v3[_callback]() and
81       java_demangle_v3[_callback]().
82
83    IN_GLIBCPP_V3
84       If defined, this file defines only __cxa_demangle() and
85       __gcclibcxx_demangle_callback(), and no other publically visible
86       functions or variables.
87
88    STANDALONE_DEMANGLER
89       If defined, this file defines a main() function which demangles
90       any arguments, or, if none, demangles stdin.
91
92    CP_DEMANGLE_DEBUG
93       If defined, turns on debugging mode, which prints information on
94       stdout about the mangled string.  This is not generally useful.
95 */
96
97 #if defined (_AIX) && !defined (__GNUC__)
98  #pragma alloca
99 #endif
100
101 #ifdef HAVE_CONFIG_H
102 #include "config.h"
103 #endif
104
105 #include <stdio.h>
106
107 #ifdef HAVE_STDLIB_H
108 #include <stdlib.h>
109 #endif
110 #ifdef HAVE_STRING_H
111 #include <string.h>
112 #endif
113
114 #ifdef HAVE_ALLOCA_H
115 # include <alloca.h>
116 #else
117 # ifndef alloca
118 #  ifdef __GNUC__
119 #   define alloca __builtin_alloca
120 #  else
121 extern char *alloca ();
122 #  endif /* __GNUC__ */
123 # endif /* alloca */
124 #endif /* HAVE_ALLOCA_H */
125
126 #include "ansidecl.h"
127 #include "libiberty.h"
128 #include "demangle.h"
129 #include "cp-demangle.h"
130
131 /* If IN_GLIBCPP_V3 is defined, some functions are made static.  We
132    also rename them via #define to avoid compiler errors when the
133    static definition conflicts with the extern declaration in a header
134    file.  */
135 #ifdef IN_GLIBCPP_V3
136
137 #define CP_STATIC_IF_GLIBCPP_V3 static
138
139 #define cplus_demangle_fill_name d_fill_name
140 static int d_fill_name (struct demangle_component *, const char *, int);
141
142 #define cplus_demangle_fill_extended_operator d_fill_extended_operator
143 static int
144 d_fill_extended_operator (struct demangle_component *, int,
145                           struct demangle_component *);
146
147 #define cplus_demangle_fill_ctor d_fill_ctor
148 static int
149 d_fill_ctor (struct demangle_component *, enum gnu_v3_ctor_kinds,
150              struct demangle_component *);
151
152 #define cplus_demangle_fill_dtor d_fill_dtor
153 static int
154 d_fill_dtor (struct demangle_component *, enum gnu_v3_dtor_kinds,
155              struct demangle_component *);
156
157 #define cplus_demangle_mangled_name d_mangled_name
158 static struct demangle_component *d_mangled_name (struct d_info *, int);
159
160 #define cplus_demangle_type d_type
161 static struct demangle_component *d_type (struct d_info *);
162
163 #define cplus_demangle_print d_print
164 static char *d_print (int, const struct demangle_component *, int, size_t *);
165
166 #define cplus_demangle_print_callback d_print_callback
167 static int d_print_callback (int, const struct demangle_component *,
168                              demangle_callbackref, void *);
169
170 #define cplus_demangle_init_info d_init_info
171 static void d_init_info (const char *, int, size_t, struct d_info *);
172
173 #else /* ! defined(IN_GLIBCPP_V3) */
174 #define CP_STATIC_IF_GLIBCPP_V3
175 #endif /* ! defined(IN_GLIBCPP_V3) */
176
177 /* See if the compiler supports dynamic arrays.  */
178
179 #ifdef __GNUC__
180 #define CP_DYNAMIC_ARRAYS
181 #else
182 #ifdef __STDC__
183 #ifdef __STDC_VERSION__
184 #if __STDC_VERSION__ >= 199901L
185 #define CP_DYNAMIC_ARRAYS
186 #endif /* __STDC__VERSION >= 199901L */
187 #endif /* defined (__STDC_VERSION__) */
188 #endif /* defined (__STDC__) */
189 #endif /* ! defined (__GNUC__) */
190
191 /* We avoid pulling in the ctype tables, to prevent pulling in
192    additional unresolved symbols when this code is used in a library.
193    FIXME: Is this really a valid reason?  This comes from the original
194    V3 demangler code.
195
196    As of this writing this file has the following undefined references
197    when compiled with -DIN_GLIBCPP_V3: realloc, free, memcpy, strcpy,
198    strcat, strlen.  */
199
200 #define IS_DIGIT(c) ((c) >= '0' && (c) <= '9')
201 #define IS_UPPER(c) ((c) >= 'A' && (c) <= 'Z')
202 #define IS_LOWER(c) ((c) >= 'a' && (c) <= 'z')
203
204 /* The prefix prepended by GCC to an identifier represnting the
205    anonymous namespace.  */
206 #define ANONYMOUS_NAMESPACE_PREFIX "_GLOBAL_"
207 #define ANONYMOUS_NAMESPACE_PREFIX_LEN \
208   (sizeof (ANONYMOUS_NAMESPACE_PREFIX) - 1)
209
210 /* Information we keep for the standard substitutions.  */
211
212 struct d_standard_sub_info
213 {
214   /* The code for this substitution.  */
215   char code;
216   /* The simple string it expands to.  */
217   const char *simple_expansion;
218   /* The length of the simple expansion.  */
219   int simple_len;
220   /* The results of a full, verbose, expansion.  This is used when
221      qualifying a constructor/destructor, or when in verbose mode.  */
222   const char *full_expansion;
223   /* The length of the full expansion.  */
224   int full_len;
225   /* What to set the last_name field of d_info to; NULL if we should
226      not set it.  This is only relevant when qualifying a
227      constructor/destructor.  */
228   const char *set_last_name;
229   /* The length of set_last_name.  */
230   int set_last_name_len;
231 };
232
233 /* Accessors for subtrees of struct demangle_component.  */
234
235 #define d_left(dc) ((dc)->u.s_binary.left)
236 #define d_right(dc) ((dc)->u.s_binary.right)
237
238 /* A list of templates.  This is used while printing.  */
239
240 struct d_print_template
241 {
242   /* Next template on the list.  */
243   struct d_print_template *next;
244   /* This template.  */
245   const struct demangle_component *template_decl;
246 };
247
248 /* A list of type modifiers.  This is used while printing.  */
249
250 struct d_print_mod
251 {
252   /* Next modifier on the list.  These are in the reverse of the order
253      in which they appeared in the mangled string.  */
254   struct d_print_mod *next;
255   /* The modifier.  */
256   const struct demangle_component *mod;
257   /* Whether this modifier was printed.  */
258   int printed;
259   /* The list of templates which applies to this modifier.  */
260   struct d_print_template *templates;
261 };
262
263 /* We use these structures to hold information during printing.  */
264
265 struct d_growable_string
266 {
267   /* Buffer holding the result.  */
268   char *buf;
269   /* Current length of data in buffer.  */
270   size_t len;
271   /* Allocated size of buffer.  */
272   size_t alc;
273   /* Set to 1 if we had a memory allocation failure.  */
274   int allocation_failure;
275 };
276
277 enum { D_PRINT_BUFFER_LENGTH = 256 };
278 struct d_print_info
279 {
280   /* The options passed to the demangler.  */
281   int options;
282   /* Fixed-length allocated buffer for demangled data, flushed to the
283      callback with a NUL termination once full.  */
284   char buf[D_PRINT_BUFFER_LENGTH];
285   /* Current length of data in buffer.  */
286   size_t len;
287   /* The last character printed, saved individually so that it survives
288      any buffer flush.  */
289   char last_char;
290   /* Callback function to handle demangled buffer flush.  */
291   demangle_callbackref callback;
292   /* Opaque callback argument.  */
293   void *opaque;
294   /* The current list of templates, if any.  */
295   struct d_print_template *templates;
296   /* The current list of modifiers (e.g., pointer, reference, etc.),
297      if any.  */
298   struct d_print_mod *modifiers;
299   /* Set to 1 if we saw a demangling error.  */
300   int demangle_failure;
301 };
302
303 #ifdef CP_DEMANGLE_DEBUG
304 static void d_dump (struct demangle_component *, int);
305 #endif
306
307 static struct demangle_component *
308 d_make_empty (struct d_info *);
309
310 static struct demangle_component *
311 d_make_comp (struct d_info *, enum demangle_component_type,
312              struct demangle_component *,
313              struct demangle_component *);
314
315 static struct demangle_component *
316 d_make_name (struct d_info *, const char *, int);
317
318 static struct demangle_component *
319 d_make_builtin_type (struct d_info *,
320                      const struct demangle_builtin_type_info *);
321
322 static struct demangle_component *
323 d_make_operator (struct d_info *,
324                  const struct demangle_operator_info *);
325
326 static struct demangle_component *
327 d_make_extended_operator (struct d_info *, int,
328                           struct demangle_component *);
329
330 static struct demangle_component *
331 d_make_ctor (struct d_info *, enum gnu_v3_ctor_kinds,
332              struct demangle_component *);
333
334 static struct demangle_component *
335 d_make_dtor (struct d_info *, enum gnu_v3_dtor_kinds,
336              struct demangle_component *);
337
338 static struct demangle_component *
339 d_make_template_param (struct d_info *, long);
340
341 static struct demangle_component *
342 d_make_sub (struct d_info *, const char *, int);
343
344 static int
345 has_return_type (struct demangle_component *);
346
347 static int
348 is_ctor_dtor_or_conversion (struct demangle_component *);
349
350 static struct demangle_component *d_encoding (struct d_info *, int);
351
352 static struct demangle_component *d_name (struct d_info *);
353
354 static struct demangle_component *d_nested_name (struct d_info *);
355
356 static struct demangle_component *d_prefix (struct d_info *);
357
358 static struct demangle_component *d_unqualified_name (struct d_info *);
359
360 static struct demangle_component *d_source_name (struct d_info *);
361
362 static long d_number (struct d_info *);
363
364 static struct demangle_component *d_identifier (struct d_info *, int);
365
366 static struct demangle_component *d_operator_name (struct d_info *);
367
368 static struct demangle_component *d_special_name (struct d_info *);
369
370 static int d_call_offset (struct d_info *, int);
371
372 static struct demangle_component *d_ctor_dtor_name (struct d_info *);
373
374 static struct demangle_component **
375 d_cv_qualifiers (struct d_info *, struct demangle_component **, int);
376
377 static struct demangle_component *
378 d_function_type (struct d_info *);
379
380 static struct demangle_component *
381 d_bare_function_type (struct d_info *, int);
382
383 static struct demangle_component *
384 d_class_enum_type (struct d_info *);
385
386 static struct demangle_component *d_array_type (struct d_info *);
387
388 static struct demangle_component *
389 d_pointer_to_member_type (struct d_info *);
390
391 static struct demangle_component *
392 d_template_param (struct d_info *);
393
394 static struct demangle_component *d_template_args (struct d_info *);
395
396 static struct demangle_component *
397 d_template_arg (struct d_info *);
398
399 static struct demangle_component *d_expression (struct d_info *);
400
401 static struct demangle_component *d_expr_primary (struct d_info *);
402
403 static struct demangle_component *d_local_name (struct d_info *);
404
405 static int d_discriminator (struct d_info *);
406
407 static int
408 d_add_substitution (struct d_info *, struct demangle_component *);
409
410 static struct demangle_component *d_substitution (struct d_info *, int);
411
412 static void d_growable_string_init (struct d_growable_string *, size_t);
413
414 static inline void
415 d_growable_string_resize (struct d_growable_string *, size_t);
416
417 static inline void
418 d_growable_string_append_buffer (struct d_growable_string *,
419                                  const char *, size_t);
420 static void
421 d_growable_string_callback_adapter (const char *, size_t, void *);
422
423 static void
424 d_print_init (struct d_print_info *, int, demangle_callbackref, void *);
425
426 static inline void d_print_error (struct d_print_info *);
427
428 static inline int d_print_saw_error (struct d_print_info *);
429
430 static inline void d_print_flush (struct d_print_info *);
431
432 static inline void d_append_char (struct d_print_info *, char);
433
434 static inline void d_append_buffer (struct d_print_info *,
435                                     const char *, size_t);
436
437 static inline void d_append_string (struct d_print_info *, const char *);
438
439 static inline char d_last_char (struct d_print_info *);
440
441 static void
442 d_print_comp (struct d_print_info *, const struct demangle_component *);
443
444 static void
445 d_print_java_identifier (struct d_print_info *, const char *, int);
446
447 static void
448 d_print_mod_list (struct d_print_info *, struct d_print_mod *, int);
449
450 static void
451 d_print_mod (struct d_print_info *, const struct demangle_component *);
452
453 static void
454 d_print_function_type (struct d_print_info *,
455                        const struct demangle_component *,
456                        struct d_print_mod *);
457
458 static void
459 d_print_array_type (struct d_print_info *,
460                     const struct demangle_component *,
461                     struct d_print_mod *);
462
463 static void
464 d_print_expr_op (struct d_print_info *, const struct demangle_component *);
465
466 static void
467 d_print_cast (struct d_print_info *, const struct demangle_component *);
468
469 static int d_demangle_callback (const char *, int,
470                                 demangle_callbackref, void *);
471 static char *d_demangle (const char *, int, size_t *);
472
473 #ifdef CP_DEMANGLE_DEBUG
474
475 static void
476 d_dump (struct demangle_component *dc, int indent)
477 {
478   int i;
479
480   if (dc == NULL)
481     {
482       if (indent == 0)
483         printf ("failed demangling\n");
484       return;
485     }
486
487   for (i = 0; i < indent; ++i)
488     putchar (' ');
489
490   switch (dc->type)
491     {
492     case DEMANGLE_COMPONENT_NAME:
493       printf ("name '%.*s'\n", dc->u.s_name.len, dc->u.s_name.s);
494       return;
495     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
496       printf ("template parameter %ld\n", dc->u.s_number.number);
497       return;
498     case DEMANGLE_COMPONENT_CTOR:
499       printf ("constructor %d\n", (int) dc->u.s_ctor.kind);
500       d_dump (dc->u.s_ctor.name, indent + 2);
501       return;
502     case DEMANGLE_COMPONENT_DTOR:
503       printf ("destructor %d\n", (int) dc->u.s_dtor.kind);
504       d_dump (dc->u.s_dtor.name, indent + 2);
505       return;
506     case DEMANGLE_COMPONENT_SUB_STD:
507       printf ("standard substitution %s\n", dc->u.s_string.string);
508       return;
509     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
510       printf ("builtin type %s\n", dc->u.s_builtin.type->name);
511       return;
512     case DEMANGLE_COMPONENT_OPERATOR:
513       printf ("operator %s\n", dc->u.s_operator.op->name);
514       return;
515     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
516       printf ("extended operator with %d args\n",
517               dc->u.s_extended_operator.args);
518       d_dump (dc->u.s_extended_operator.name, indent + 2);
519       return;
520
521     case DEMANGLE_COMPONENT_QUAL_NAME:
522       printf ("qualified name\n");
523       break;
524     case DEMANGLE_COMPONENT_LOCAL_NAME:
525       printf ("local name\n");
526       break;
527     case DEMANGLE_COMPONENT_TYPED_NAME:
528       printf ("typed name\n");
529       break;
530     case DEMANGLE_COMPONENT_TEMPLATE:
531       printf ("template\n");
532       break;
533     case DEMANGLE_COMPONENT_VTABLE:
534       printf ("vtable\n");
535       break;
536     case DEMANGLE_COMPONENT_VTT:
537       printf ("VTT\n");
538       break;
539     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
540       printf ("construction vtable\n");
541       break;
542     case DEMANGLE_COMPONENT_TYPEINFO:
543       printf ("typeinfo\n");
544       break;
545     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
546       printf ("typeinfo name\n");
547       break;
548     case DEMANGLE_COMPONENT_TYPEINFO_FN:
549       printf ("typeinfo function\n");
550       break;
551     case DEMANGLE_COMPONENT_THUNK:
552       printf ("thunk\n");
553       break;
554     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
555       printf ("virtual thunk\n");
556       break;
557     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
558       printf ("covariant thunk\n");
559       break;
560     case DEMANGLE_COMPONENT_JAVA_CLASS:
561       printf ("java class\n");
562       break;
563     case DEMANGLE_COMPONENT_GUARD:
564       printf ("guard\n");
565       break;
566     case DEMANGLE_COMPONENT_REFTEMP:
567       printf ("reference temporary\n");
568       break;
569     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
570       printf ("hidden alias\n");
571       break;
572     case DEMANGLE_COMPONENT_RESTRICT:
573       printf ("restrict\n");
574       break;
575     case DEMANGLE_COMPONENT_VOLATILE:
576       printf ("volatile\n");
577       break;
578     case DEMANGLE_COMPONENT_CONST:
579       printf ("const\n");
580       break;
581     case DEMANGLE_COMPONENT_RESTRICT_THIS:
582       printf ("restrict this\n");
583       break;
584     case DEMANGLE_COMPONENT_VOLATILE_THIS:
585       printf ("volatile this\n");
586       break;
587     case DEMANGLE_COMPONENT_CONST_THIS:
588       printf ("const this\n");
589       break;
590     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
591       printf ("vendor type qualifier\n");
592       break;
593     case DEMANGLE_COMPONENT_POINTER:
594       printf ("pointer\n");
595       break;
596     case DEMANGLE_COMPONENT_REFERENCE:
597       printf ("reference\n");
598       break;
599     case DEMANGLE_COMPONENT_COMPLEX:
600       printf ("complex\n");
601       break;
602     case DEMANGLE_COMPONENT_IMAGINARY:
603       printf ("imaginary\n");
604       break;
605     case DEMANGLE_COMPONENT_VENDOR_TYPE:
606       printf ("vendor type\n");
607       break;
608     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
609       printf ("function type\n");
610       break;
611     case DEMANGLE_COMPONENT_ARRAY_TYPE:
612       printf ("array type\n");
613       break;
614     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
615       printf ("pointer to member type\n");
616       break;
617     case DEMANGLE_COMPONENT_ARGLIST:
618       printf ("argument list\n");
619       break;
620     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
621       printf ("template argument list\n");
622       break;
623     case DEMANGLE_COMPONENT_CAST:
624       printf ("cast\n");
625       break;
626     case DEMANGLE_COMPONENT_UNARY:
627       printf ("unary operator\n");
628       break;
629     case DEMANGLE_COMPONENT_BINARY:
630       printf ("binary operator\n");
631       break;
632     case DEMANGLE_COMPONENT_BINARY_ARGS:
633       printf ("binary operator arguments\n");
634       break;
635     case DEMANGLE_COMPONENT_TRINARY:
636       printf ("trinary operator\n");
637       break;
638     case DEMANGLE_COMPONENT_TRINARY_ARG1:
639       printf ("trinary operator arguments 1\n");
640       break;
641     case DEMANGLE_COMPONENT_TRINARY_ARG2:
642       printf ("trinary operator arguments 1\n");
643       break;
644     case DEMANGLE_COMPONENT_LITERAL:
645       printf ("literal\n");
646       break;
647     case DEMANGLE_COMPONENT_LITERAL_NEG:
648       printf ("negative literal\n");
649       break;
650     }
651
652   d_dump (d_left (dc), indent + 2);
653   d_dump (d_right (dc), indent + 2);
654 }
655
656 #endif /* CP_DEMANGLE_DEBUG */
657
658 /* Fill in a DEMANGLE_COMPONENT_NAME.  */
659
660 CP_STATIC_IF_GLIBCPP_V3
661 int
662 cplus_demangle_fill_name (struct demangle_component *p, const char *s, int len)
663 {
664   if (p == NULL || s == NULL || len == 0)
665     return 0;
666   p->type = DEMANGLE_COMPONENT_NAME;
667   p->u.s_name.s = s;
668   p->u.s_name.len = len;
669   return 1;
670 }
671
672 /* Fill in a DEMANGLE_COMPONENT_EXTENDED_OPERATOR.  */
673
674 CP_STATIC_IF_GLIBCPP_V3
675 int
676 cplus_demangle_fill_extended_operator (struct demangle_component *p, int args,
677                                        struct demangle_component *name)
678 {
679   if (p == NULL || args < 0 || name == NULL)
680     return 0;
681   p->type = DEMANGLE_COMPONENT_EXTENDED_OPERATOR;
682   p->u.s_extended_operator.args = args;
683   p->u.s_extended_operator.name = name;
684   return 1;
685 }
686
687 /* Fill in a DEMANGLE_COMPONENT_CTOR.  */
688
689 CP_STATIC_IF_GLIBCPP_V3
690 int
691 cplus_demangle_fill_ctor (struct demangle_component *p,
692                           enum gnu_v3_ctor_kinds kind,
693                           struct demangle_component *name)
694 {
695   if (p == NULL
696       || name == NULL
697       || (kind < gnu_v3_complete_object_ctor
698           && kind > gnu_v3_complete_object_allocating_ctor))
699     return 0;
700   p->type = DEMANGLE_COMPONENT_CTOR;
701   p->u.s_ctor.kind = kind;
702   p->u.s_ctor.name = name;
703   return 1;
704 }
705
706 /* Fill in a DEMANGLE_COMPONENT_DTOR.  */
707
708 CP_STATIC_IF_GLIBCPP_V3
709 int
710 cplus_demangle_fill_dtor (struct demangle_component *p,
711                           enum gnu_v3_dtor_kinds kind,
712                           struct demangle_component *name)
713 {
714   if (p == NULL
715       || name == NULL
716       || (kind < gnu_v3_deleting_dtor
717           && kind > gnu_v3_base_object_dtor))
718     return 0;
719   p->type = DEMANGLE_COMPONENT_DTOR;
720   p->u.s_dtor.kind = kind;
721   p->u.s_dtor.name = name;
722   return 1;
723 }
724
725 /* Add a new component.  */
726
727 static struct demangle_component *
728 d_make_empty (struct d_info *di)
729 {
730   struct demangle_component *p;
731
732   if (di->next_comp >= di->num_comps)
733     return NULL;
734   p = &di->comps[di->next_comp];
735   ++di->next_comp;
736   return p;
737 }
738
739 /* Add a new generic component.  */
740
741 static struct demangle_component *
742 d_make_comp (struct d_info *di, enum demangle_component_type type,
743              struct demangle_component *left,
744              struct demangle_component *right)
745 {
746   struct demangle_component *p;
747
748   /* We check for errors here.  A typical error would be a NULL return
749      from a subroutine.  We catch those here, and return NULL
750      upward.  */
751   switch (type)
752     {
753       /* These types require two parameters.  */
754     case DEMANGLE_COMPONENT_QUAL_NAME:
755     case DEMANGLE_COMPONENT_LOCAL_NAME:
756     case DEMANGLE_COMPONENT_TYPED_NAME:
757     case DEMANGLE_COMPONENT_TEMPLATE:
758     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
759     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
760     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
761     case DEMANGLE_COMPONENT_UNARY:
762     case DEMANGLE_COMPONENT_BINARY:
763     case DEMANGLE_COMPONENT_BINARY_ARGS:
764     case DEMANGLE_COMPONENT_TRINARY:
765     case DEMANGLE_COMPONENT_TRINARY_ARG1:
766     case DEMANGLE_COMPONENT_TRINARY_ARG2:
767     case DEMANGLE_COMPONENT_LITERAL:
768     case DEMANGLE_COMPONENT_LITERAL_NEG:
769       if (left == NULL || right == NULL)
770         return NULL;
771       break;
772
773       /* These types only require one parameter.  */
774     case DEMANGLE_COMPONENT_VTABLE:
775     case DEMANGLE_COMPONENT_VTT:
776     case DEMANGLE_COMPONENT_TYPEINFO:
777     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
778     case DEMANGLE_COMPONENT_TYPEINFO_FN:
779     case DEMANGLE_COMPONENT_THUNK:
780     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
781     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
782     case DEMANGLE_COMPONENT_JAVA_CLASS:
783     case DEMANGLE_COMPONENT_GUARD:
784     case DEMANGLE_COMPONENT_REFTEMP:
785     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
786     case DEMANGLE_COMPONENT_POINTER:
787     case DEMANGLE_COMPONENT_REFERENCE:
788     case DEMANGLE_COMPONENT_COMPLEX:
789     case DEMANGLE_COMPONENT_IMAGINARY:
790     case DEMANGLE_COMPONENT_VENDOR_TYPE:
791     case DEMANGLE_COMPONENT_ARGLIST:
792     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
793     case DEMANGLE_COMPONENT_CAST:
794       if (left == NULL)
795         return NULL;
796       break;
797
798       /* This needs a right parameter, but the left parameter can be
799          empty.  */
800     case DEMANGLE_COMPONENT_ARRAY_TYPE:
801       if (right == NULL)
802         return NULL;
803       break;
804
805       /* These are allowed to have no parameters--in some cases they
806          will be filled in later.  */
807     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
808     case DEMANGLE_COMPONENT_RESTRICT:
809     case DEMANGLE_COMPONENT_VOLATILE:
810     case DEMANGLE_COMPONENT_CONST:
811     case DEMANGLE_COMPONENT_RESTRICT_THIS:
812     case DEMANGLE_COMPONENT_VOLATILE_THIS:
813     case DEMANGLE_COMPONENT_CONST_THIS:
814       break;
815
816       /* Other types should not be seen here.  */
817     default:
818       return NULL;
819     }
820
821   p = d_make_empty (di);
822   if (p != NULL)
823     {
824       p->type = type;
825       p->u.s_binary.left = left;
826       p->u.s_binary.right = right;
827     }
828   return p;
829 }
830
831 /* Add a new name component.  */
832
833 static struct demangle_component *
834 d_make_name (struct d_info *di, const char *s, int len)
835 {
836   struct demangle_component *p;
837
838   p = d_make_empty (di);
839   if (! cplus_demangle_fill_name (p, s, len))
840     return NULL;
841   return p;
842 }
843
844 /* Add a new builtin type component.  */
845
846 static struct demangle_component *
847 d_make_builtin_type (struct d_info *di,
848                      const struct demangle_builtin_type_info *type)
849 {
850   struct demangle_component *p;
851
852   if (type == NULL)
853     return NULL;
854   p = d_make_empty (di);
855   if (p != NULL)
856     {
857       p->type = DEMANGLE_COMPONENT_BUILTIN_TYPE;
858       p->u.s_builtin.type = type;
859     }
860   return p;
861 }
862
863 /* Add a new operator component.  */
864
865 static struct demangle_component *
866 d_make_operator (struct d_info *di, const struct demangle_operator_info *op)
867 {
868   struct demangle_component *p;
869
870   p = d_make_empty (di);
871   if (p != NULL)
872     {
873       p->type = DEMANGLE_COMPONENT_OPERATOR;
874       p->u.s_operator.op = op;
875     }
876   return p;
877 }
878
879 /* Add a new extended operator component.  */
880
881 static struct demangle_component *
882 d_make_extended_operator (struct d_info *di, int args,
883                           struct demangle_component *name)
884 {
885   struct demangle_component *p;
886
887   p = d_make_empty (di);
888   if (! cplus_demangle_fill_extended_operator (p, args, name))
889     return NULL;
890   return p;
891 }
892
893 /* Add a new constructor component.  */
894
895 static struct demangle_component *
896 d_make_ctor (struct d_info *di, enum gnu_v3_ctor_kinds kind,
897              struct demangle_component *name)
898 {
899   struct demangle_component *p;
900
901   p = d_make_empty (di);
902   if (! cplus_demangle_fill_ctor (p, kind, name))
903     return NULL;
904   return p;
905 }
906
907 /* Add a new destructor component.  */
908
909 static struct demangle_component *
910 d_make_dtor (struct d_info *di, enum gnu_v3_dtor_kinds kind,
911              struct demangle_component *name)
912 {
913   struct demangle_component *p;
914
915   p = d_make_empty (di);
916   if (! cplus_demangle_fill_dtor (p, kind, name))
917     return NULL;
918   return p;
919 }
920
921 /* Add a new template parameter.  */
922
923 static struct demangle_component *
924 d_make_template_param (struct d_info *di, long i)
925 {
926   struct demangle_component *p;
927
928   p = d_make_empty (di);
929   if (p != NULL)
930     {
931       p->type = DEMANGLE_COMPONENT_TEMPLATE_PARAM;
932       p->u.s_number.number = i;
933     }
934   return p;
935 }
936
937 /* Add a new standard substitution component.  */
938
939 static struct demangle_component *
940 d_make_sub (struct d_info *di, const char *name, int len)
941 {
942   struct demangle_component *p;
943
944   p = d_make_empty (di);
945   if (p != NULL)
946     {
947       p->type = DEMANGLE_COMPONENT_SUB_STD;
948       p->u.s_string.string = name;
949       p->u.s_string.len = len;
950     }
951   return p;
952 }
953
954 /* <mangled-name> ::= _Z <encoding>
955
956    TOP_LEVEL is non-zero when called at the top level.  */
957
958 CP_STATIC_IF_GLIBCPP_V3
959 struct demangle_component *
960 cplus_demangle_mangled_name (struct d_info *di, int top_level)
961 {
962   if (! d_check_char (di, '_'))
963     return NULL;
964   if (! d_check_char (di, 'Z'))
965     return NULL;
966   return d_encoding (di, top_level);
967 }
968
969 /* Return whether a function should have a return type.  The argument
970    is the function name, which may be qualified in various ways.  The
971    rules are that template functions have return types with some
972    exceptions, function types which are not part of a function name
973    mangling have return types with some exceptions, and non-template
974    function names do not have return types.  The exceptions are that
975    constructors, destructors, and conversion operators do not have
976    return types.  */
977
978 static int
979 has_return_type (struct demangle_component *dc)
980 {
981   if (dc == NULL)
982     return 0;
983   switch (dc->type)
984     {
985     default:
986       return 0;
987     case DEMANGLE_COMPONENT_TEMPLATE:
988       return ! is_ctor_dtor_or_conversion (d_left (dc));
989     case DEMANGLE_COMPONENT_RESTRICT_THIS:
990     case DEMANGLE_COMPONENT_VOLATILE_THIS:
991     case DEMANGLE_COMPONENT_CONST_THIS:
992       return has_return_type (d_left (dc));
993     }
994 }
995
996 /* Return whether a name is a constructor, a destructor, or a
997    conversion operator.  */
998
999 static int
1000 is_ctor_dtor_or_conversion (struct demangle_component *dc)
1001 {
1002   if (dc == NULL)
1003     return 0;
1004   switch (dc->type)
1005     {
1006     default:
1007       return 0;
1008     case DEMANGLE_COMPONENT_QUAL_NAME:
1009     case DEMANGLE_COMPONENT_LOCAL_NAME:
1010       return is_ctor_dtor_or_conversion (d_right (dc));
1011     case DEMANGLE_COMPONENT_CTOR:
1012     case DEMANGLE_COMPONENT_DTOR:
1013     case DEMANGLE_COMPONENT_CAST:
1014       return 1;
1015     }
1016 }
1017
1018 /* <encoding> ::= <(function) name> <bare-function-type>
1019               ::= <(data) name>
1020               ::= <special-name>
1021
1022    TOP_LEVEL is non-zero when called at the top level, in which case
1023    if DMGL_PARAMS is not set we do not demangle the function
1024    parameters.  We only set this at the top level, because otherwise
1025    we would not correctly demangle names in local scopes.  */
1026
1027 static struct demangle_component *
1028 d_encoding (struct d_info *di, int top_level)
1029 {
1030   char peek = d_peek_char (di);
1031
1032   if (peek == 'G' || peek == 'T')
1033     return d_special_name (di);
1034   else
1035     {
1036       struct demangle_component *dc;
1037
1038       dc = d_name (di);
1039
1040       if (dc != NULL && top_level && (di->options & DMGL_PARAMS) == 0)
1041         {
1042           /* Strip off any initial CV-qualifiers, as they really apply
1043              to the `this' parameter, and they were not output by the
1044              v2 demangler without DMGL_PARAMS.  */
1045           while (dc->type == DEMANGLE_COMPONENT_RESTRICT_THIS
1046                  || dc->type == DEMANGLE_COMPONENT_VOLATILE_THIS
1047                  || dc->type == DEMANGLE_COMPONENT_CONST_THIS)
1048             dc = d_left (dc);
1049
1050           /* If the top level is a DEMANGLE_COMPONENT_LOCAL_NAME, then
1051              there may be CV-qualifiers on its right argument which
1052              really apply here; this happens when parsing a class
1053              which is local to a function.  */
1054           if (dc->type == DEMANGLE_COMPONENT_LOCAL_NAME)
1055             {
1056               struct demangle_component *dcr;
1057
1058               dcr = d_right (dc);
1059               while (dcr->type == DEMANGLE_COMPONENT_RESTRICT_THIS
1060                      || dcr->type == DEMANGLE_COMPONENT_VOLATILE_THIS
1061                      || dcr->type == DEMANGLE_COMPONENT_CONST_THIS)
1062                 dcr = d_left (dcr);
1063               dc->u.s_binary.right = dcr;
1064             }
1065
1066           return dc;
1067         }
1068
1069       peek = d_peek_char (di);
1070       if (peek == '\0' || peek == 'E')
1071         return dc;
1072       return d_make_comp (di, DEMANGLE_COMPONENT_TYPED_NAME, dc,
1073                           d_bare_function_type (di, has_return_type (dc)));
1074     }
1075 }
1076
1077 /* <name> ::= <nested-name>
1078           ::= <unscoped-name>
1079           ::= <unscoped-template-name> <template-args>
1080           ::= <local-name>
1081
1082    <unscoped-name> ::= <unqualified-name>
1083                    ::= St <unqualified-name>
1084
1085    <unscoped-template-name> ::= <unscoped-name>
1086                             ::= <substitution>
1087 */
1088
1089 static struct demangle_component *
1090 d_name (struct d_info *di)
1091 {
1092   char peek = d_peek_char (di);
1093   struct demangle_component *dc;
1094
1095   switch (peek)
1096     {
1097     case 'N':
1098       return d_nested_name (di);
1099
1100     case 'Z':
1101       return d_local_name (di);
1102
1103     case 'S':
1104       {
1105         int subst;
1106
1107         if (d_peek_next_char (di) != 't')
1108           {
1109             dc = d_substitution (di, 0);
1110             subst = 1;
1111           }
1112         else
1113           {
1114             d_advance (di, 2);
1115             dc = d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME,
1116                               d_make_name (di, "std", 3),
1117                               d_unqualified_name (di));
1118             di->expansion += 3;
1119             subst = 0;
1120           }
1121
1122         if (d_peek_char (di) != 'I')
1123           {
1124             /* The grammar does not permit this case to occur if we
1125                called d_substitution() above (i.e., subst == 1).  We
1126                don't bother to check.  */
1127           }
1128         else
1129           {
1130             /* This is <template-args>, which means that we just saw
1131                <unscoped-template-name>, which is a substitution
1132                candidate if we didn't just get it from a
1133                substitution.  */
1134             if (! subst)
1135               {
1136                 if (! d_add_substitution (di, dc))
1137                   return NULL;
1138               }
1139             dc = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, dc,
1140                               d_template_args (di));
1141           }
1142
1143         return dc;
1144       }
1145
1146     default:
1147       dc = d_unqualified_name (di);
1148       if (d_peek_char (di) == 'I')
1149         {
1150           /* This is <template-args>, which means that we just saw
1151              <unscoped-template-name>, which is a substitution
1152              candidate.  */
1153           if (! d_add_substitution (di, dc))
1154             return NULL;
1155           dc = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, dc,
1156                             d_template_args (di));
1157         }
1158       return dc;
1159     }
1160 }
1161
1162 /* <nested-name> ::= N [<CV-qualifiers>] <prefix> <unqualified-name> E
1163                  ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1164 */
1165
1166 static struct demangle_component *
1167 d_nested_name (struct d_info *di)
1168 {
1169   struct demangle_component *ret;
1170   struct demangle_component **pret;
1171
1172   if (! d_check_char (di, 'N'))
1173     return NULL;
1174
1175   pret = d_cv_qualifiers (di, &ret, 1);
1176   if (pret == NULL)
1177     return NULL;
1178
1179   *pret = d_prefix (di);
1180   if (*pret == NULL)
1181     return NULL;
1182
1183   if (! d_check_char (di, 'E'))
1184     return NULL;
1185
1186   return ret;
1187 }
1188
1189 /* <prefix> ::= <prefix> <unqualified-name>
1190             ::= <template-prefix> <template-args>
1191             ::= <template-param>
1192             ::=
1193             ::= <substitution>
1194
1195    <template-prefix> ::= <prefix> <(template) unqualified-name>
1196                      ::= <template-param>
1197                      ::= <substitution>
1198 */
1199
1200 static struct demangle_component *
1201 d_prefix (struct d_info *di)
1202 {
1203   struct demangle_component *ret = NULL;
1204
1205   while (1)
1206     {
1207       char peek;
1208       enum demangle_component_type comb_type;
1209       struct demangle_component *dc;
1210
1211       peek = d_peek_char (di);
1212       if (peek == '\0')
1213         return NULL;
1214
1215       /* The older code accepts a <local-name> here, but I don't see
1216          that in the grammar.  The older code does not accept a
1217          <template-param> here.  */
1218
1219       comb_type = DEMANGLE_COMPONENT_QUAL_NAME;
1220       if (IS_DIGIT (peek)
1221           || IS_LOWER (peek)
1222           || peek == 'C'
1223           || peek == 'D')
1224         dc = d_unqualified_name (di);
1225       else if (peek == 'S')
1226         dc = d_substitution (di, 1);
1227       else if (peek == 'I')
1228         {
1229           if (ret == NULL)
1230             return NULL;
1231           comb_type = DEMANGLE_COMPONENT_TEMPLATE;
1232           dc = d_template_args (di);
1233         }
1234       else if (peek == 'T')
1235         dc = d_template_param (di);
1236       else if (peek == 'E')
1237         return ret;
1238       else
1239         return NULL;
1240
1241       if (ret == NULL)
1242         ret = dc;
1243       else
1244         ret = d_make_comp (di, comb_type, ret, dc);
1245
1246       if (peek != 'S' && d_peek_char (di) != 'E')
1247         {
1248           if (! d_add_substitution (di, ret))
1249             return NULL;
1250         }
1251     }
1252 }
1253
1254 /* <unqualified-name> ::= <operator-name>
1255                       ::= <ctor-dtor-name>
1256                       ::= <source-name>
1257 */
1258
1259 static struct demangle_component *
1260 d_unqualified_name (struct d_info *di)
1261 {
1262   char peek;
1263
1264   peek = d_peek_char (di);
1265   if (IS_DIGIT (peek))
1266     return d_source_name (di);
1267   else if (IS_LOWER (peek))
1268     {
1269       struct demangle_component *ret;
1270
1271       ret = d_operator_name (di);
1272       if (ret != NULL && ret->type == DEMANGLE_COMPONENT_OPERATOR)
1273         di->expansion += sizeof "operator" + ret->u.s_operator.op->len - 2;
1274       return ret;
1275     }
1276   else if (peek == 'C' || peek == 'D')
1277     return d_ctor_dtor_name (di);
1278   else
1279     return NULL;
1280 }
1281
1282 /* <source-name> ::= <(positive length) number> <identifier>  */
1283
1284 static struct demangle_component *
1285 d_source_name (struct d_info *di)
1286 {
1287   long len;
1288   struct demangle_component *ret;
1289
1290   len = d_number (di);
1291   if (len <= 0)
1292     return NULL;
1293   ret = d_identifier (di, len);
1294   di->last_name = ret;
1295   return ret;
1296 }
1297
1298 /* number ::= [n] <(non-negative decimal integer)>  */
1299
1300 static long
1301 d_number (struct d_info *di)
1302 {
1303   int negative;
1304   char peek;
1305   long ret;
1306
1307   negative = 0;
1308   peek = d_peek_char (di);
1309   if (peek == 'n')
1310     {
1311       negative = 1;
1312       d_advance (di, 1);
1313       peek = d_peek_char (di);
1314     }
1315
1316   ret = 0;
1317   while (1)
1318     {
1319       if (! IS_DIGIT (peek))
1320         {
1321           if (negative)
1322             ret = - ret;
1323           return ret;
1324         }
1325       ret = ret * 10 + peek - '0';
1326       d_advance (di, 1);
1327       peek = d_peek_char (di);
1328     }
1329 }
1330
1331 /* identifier ::= <(unqualified source code identifier)>  */
1332
1333 static struct demangle_component *
1334 d_identifier (struct d_info *di, int len)
1335 {
1336   const char *name;
1337
1338   name = d_str (di);
1339
1340   if (di->send - name < len)
1341     return NULL;
1342
1343   d_advance (di, len);
1344
1345   /* A Java mangled name may have a trailing '$' if it is a C++
1346      keyword.  This '$' is not included in the length count.  We just
1347      ignore the '$'.  */
1348   if ((di->options & DMGL_JAVA) != 0
1349       && d_peek_char (di) == '$')
1350     d_advance (di, 1);
1351
1352   /* Look for something which looks like a gcc encoding of an
1353      anonymous namespace, and replace it with a more user friendly
1354      name.  */
1355   if (len >= (int) ANONYMOUS_NAMESPACE_PREFIX_LEN + 2
1356       && memcmp (name, ANONYMOUS_NAMESPACE_PREFIX,
1357                  ANONYMOUS_NAMESPACE_PREFIX_LEN) == 0)
1358     {
1359       const char *s;
1360
1361       s = name + ANONYMOUS_NAMESPACE_PREFIX_LEN;
1362       if ((*s == '.' || *s == '_' || *s == '$')
1363           && s[1] == 'N')
1364         {
1365           di->expansion -= len - sizeof "(anonymous namespace)";
1366           return d_make_name (di, "(anonymous namespace)",
1367                               sizeof "(anonymous namespace)" - 1);
1368         }
1369     }
1370
1371   return d_make_name (di, name, len);
1372 }
1373
1374 /* operator_name ::= many different two character encodings.
1375                  ::= cv <type>
1376                  ::= v <digit> <source-name>
1377 */
1378
1379 #define NL(s) s, (sizeof s) - 1
1380
1381 CP_STATIC_IF_GLIBCPP_V3
1382 const struct demangle_operator_info cplus_demangle_operators[] =
1383 {
1384   { "aN", NL ("&="),        2 },
1385   { "aS", NL ("="),         2 },
1386   { "aa", NL ("&&"),        2 },
1387   { "ad", NL ("&"),         1 },
1388   { "an", NL ("&"),         2 },
1389   { "cl", NL ("()"),        0 },
1390   { "cm", NL (","),         2 },
1391   { "co", NL ("~"),         1 },
1392   { "dV", NL ("/="),        2 },
1393   { "da", NL ("delete[]"),  1 },
1394   { "de", NL ("*"),         1 },
1395   { "dl", NL ("delete"),    1 },
1396   { "dv", NL ("/"),         2 },
1397   { "eO", NL ("^="),        2 },
1398   { "eo", NL ("^"),         2 },
1399   { "eq", NL ("=="),        2 },
1400   { "ge", NL (">="),        2 },
1401   { "gt", NL (">"),         2 },
1402   { "ix", NL ("[]"),        2 },
1403   { "lS", NL ("<<="),       2 },
1404   { "le", NL ("<="),        2 },
1405   { "ls", NL ("<<"),        2 },
1406   { "lt", NL ("<"),         2 },
1407   { "mI", NL ("-="),        2 },
1408   { "mL", NL ("*="),        2 },
1409   { "mi", NL ("-"),         2 },
1410   { "ml", NL ("*"),         2 },
1411   { "mm", NL ("--"),        1 },
1412   { "na", NL ("new[]"),     1 },
1413   { "ne", NL ("!="),        2 },
1414   { "ng", NL ("-"),         1 },
1415   { "nt", NL ("!"),         1 },
1416   { "nw", NL ("new"),       1 },
1417   { "oR", NL ("|="),        2 },
1418   { "oo", NL ("||"),        2 },
1419   { "or", NL ("|"),         2 },
1420   { "pL", NL ("+="),        2 },
1421   { "pl", NL ("+"),         2 },
1422   { "pm", NL ("->*"),       2 },
1423   { "pp", NL ("++"),        1 },
1424   { "ps", NL ("+"),         1 },
1425   { "pt", NL ("->"),        2 },
1426   { "qu", NL ("?"),         3 },
1427   { "rM", NL ("%="),        2 },
1428   { "rS", NL (">>="),       2 },
1429   { "rm", NL ("%"),         2 },
1430   { "rs", NL (">>"),        2 },
1431   { "st", NL ("sizeof "),   1 },
1432   { "sz", NL ("sizeof "),   1 },
1433   { NULL, NULL, 0,          0 }
1434 };
1435
1436 static struct demangle_component *
1437 d_operator_name (struct d_info *di)
1438 {
1439   char c1;
1440   char c2;
1441
1442   c1 = d_next_char (di);
1443   c2 = d_next_char (di);
1444   if (c1 == 'v' && IS_DIGIT (c2))
1445     return d_make_extended_operator (di, c2 - '0', d_source_name (di));
1446   else if (c1 == 'c' && c2 == 'v')
1447     return d_make_comp (di, DEMANGLE_COMPONENT_CAST,
1448                         cplus_demangle_type (di), NULL);
1449   else
1450     {
1451       /* LOW is the inclusive lower bound.  */
1452       int low = 0;
1453       /* HIGH is the exclusive upper bound.  We subtract one to ignore
1454          the sentinel at the end of the array.  */
1455       int high = ((sizeof (cplus_demangle_operators)
1456                    / sizeof (cplus_demangle_operators[0]))
1457                   - 1);
1458
1459       while (1)
1460         {
1461           int i;
1462           const struct demangle_operator_info *p;
1463
1464           i = low + (high - low) / 2;
1465           p = cplus_demangle_operators + i;
1466
1467           if (c1 == p->code[0] && c2 == p->code[1])
1468             return d_make_operator (di, p);
1469
1470           if (c1 < p->code[0] || (c1 == p->code[0] && c2 < p->code[1]))
1471             high = i;
1472           else
1473             low = i + 1;
1474           if (low == high)
1475             return NULL;
1476         }
1477     }
1478 }
1479
1480 /* <special-name> ::= TV <type>
1481                   ::= TT <type>
1482                   ::= TI <type>
1483                   ::= TS <type>
1484                   ::= GV <(object) name>
1485                   ::= T <call-offset> <(base) encoding>
1486                   ::= Tc <call-offset> <call-offset> <(base) encoding>
1487    Also g++ extensions:
1488                   ::= TC <type> <(offset) number> _ <(base) type>
1489                   ::= TF <type>
1490                   ::= TJ <type>
1491                   ::= GR <name>
1492                   ::= GA <encoding>
1493 */
1494
1495 static struct demangle_component *
1496 d_special_name (struct d_info *di)
1497 {
1498   di->expansion += 20;
1499   if (d_check_char (di, 'T'))
1500     {
1501       switch (d_next_char (di))
1502         {
1503         case 'V':
1504           di->expansion -= 5;
1505           return d_make_comp (di, DEMANGLE_COMPONENT_VTABLE,
1506                               cplus_demangle_type (di), NULL);
1507         case 'T':
1508           di->expansion -= 10;
1509           return d_make_comp (di, DEMANGLE_COMPONENT_VTT,
1510                               cplus_demangle_type (di), NULL);
1511         case 'I':
1512           return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO,
1513                               cplus_demangle_type (di), NULL);
1514         case 'S':
1515           return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO_NAME,
1516                               cplus_demangle_type (di), NULL);
1517
1518         case 'h':
1519           if (! d_call_offset (di, 'h'))
1520             return NULL;
1521           return d_make_comp (di, DEMANGLE_COMPONENT_THUNK,
1522                               d_encoding (di, 0), NULL);
1523
1524         case 'v':
1525           if (! d_call_offset (di, 'v'))
1526             return NULL;
1527           return d_make_comp (di, DEMANGLE_COMPONENT_VIRTUAL_THUNK,
1528                               d_encoding (di, 0), NULL);
1529
1530         case 'c':
1531           if (! d_call_offset (di, '\0'))
1532             return NULL;
1533           if (! d_call_offset (di, '\0'))
1534             return NULL;
1535           return d_make_comp (di, DEMANGLE_COMPONENT_COVARIANT_THUNK,
1536                               d_encoding (di, 0), NULL);
1537
1538         case 'C':
1539           {
1540             struct demangle_component *derived_type;
1541             long offset;
1542             struct demangle_component *base_type;
1543
1544             derived_type = cplus_demangle_type (di);
1545             offset = d_number (di);
1546             if (offset < 0)
1547               return NULL;
1548             if (! d_check_char (di, '_'))
1549               return NULL;
1550             base_type = cplus_demangle_type (di);
1551             /* We don't display the offset.  FIXME: We should display
1552                it in verbose mode.  */
1553             di->expansion += 5;
1554             return d_make_comp (di, DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE,
1555                                 base_type, derived_type);
1556           }
1557
1558         case 'F':
1559           return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO_FN,
1560                               cplus_demangle_type (di), NULL);
1561         case 'J':
1562           return d_make_comp (di, DEMANGLE_COMPONENT_JAVA_CLASS,
1563                               cplus_demangle_type (di), NULL);
1564
1565         default:
1566           return NULL;
1567         }
1568     }
1569   else if (d_check_char (di, 'G'))
1570     {
1571       switch (d_next_char (di))
1572         {
1573         case 'V':
1574           return d_make_comp (di, DEMANGLE_COMPONENT_GUARD, d_name (di), NULL);
1575
1576         case 'R':
1577           return d_make_comp (di, DEMANGLE_COMPONENT_REFTEMP, d_name (di),
1578                               NULL);
1579
1580         case 'A':
1581           return d_make_comp (di, DEMANGLE_COMPONENT_HIDDEN_ALIAS,
1582                               d_encoding (di, 0), NULL);
1583
1584         default:
1585           return NULL;
1586         }
1587     }
1588   else
1589     return NULL;
1590 }
1591
1592 /* <call-offset> ::= h <nv-offset> _
1593                  ::= v <v-offset> _
1594
1595    <nv-offset> ::= <(offset) number>
1596
1597    <v-offset> ::= <(offset) number> _ <(virtual offset) number>
1598
1599    The C parameter, if not '\0', is a character we just read which is
1600    the start of the <call-offset>.
1601
1602    We don't display the offset information anywhere.  FIXME: We should
1603    display it in verbose mode.  */
1604
1605 static int
1606 d_call_offset (struct d_info *di, int c)
1607 {
1608   if (c == '\0')
1609     c = d_next_char (di);
1610
1611   if (c == 'h')
1612     d_number (di);
1613   else if (c == 'v')
1614     {
1615       d_number (di);
1616       if (! d_check_char (di, '_'))
1617         return 0;
1618       d_number (di);
1619     }
1620   else
1621     return 0;
1622
1623   if (! d_check_char (di, '_'))
1624     return 0;
1625
1626   return 1;
1627 }
1628
1629 /* <ctor-dtor-name> ::= C1
1630                     ::= C2
1631                     ::= C3
1632                     ::= D0
1633                     ::= D1
1634                     ::= D2
1635 */
1636
1637 static struct demangle_component *
1638 d_ctor_dtor_name (struct d_info *di)
1639 {
1640   if (di->last_name != NULL)
1641     {
1642       if (di->last_name->type == DEMANGLE_COMPONENT_NAME)
1643         di->expansion += di->last_name->u.s_name.len;
1644       else if (di->last_name->type == DEMANGLE_COMPONENT_SUB_STD)
1645         di->expansion += di->last_name->u.s_string.len;
1646     }
1647   switch (d_peek_char (di))
1648     {
1649     case 'C':
1650       {
1651         enum gnu_v3_ctor_kinds kind;
1652
1653         switch (d_peek_next_char (di))
1654           {
1655           case '1':
1656             kind = gnu_v3_complete_object_ctor;
1657             break;
1658           case '2':
1659             kind = gnu_v3_base_object_ctor;
1660             break;
1661           case '3':
1662             kind = gnu_v3_complete_object_allocating_ctor;
1663             break;
1664           default:
1665             return NULL;
1666           }
1667         d_advance (di, 2);
1668         return d_make_ctor (di, kind, di->last_name);
1669       }
1670
1671     case 'D':
1672       {
1673         enum gnu_v3_dtor_kinds kind;
1674
1675         switch (d_peek_next_char (di))
1676           {
1677           case '0':
1678             kind = gnu_v3_deleting_dtor;
1679             break;
1680           case '1':
1681             kind = gnu_v3_complete_object_dtor;
1682             break;
1683           case '2':
1684             kind = gnu_v3_base_object_dtor;
1685             break;
1686           default:
1687             return NULL;
1688           }
1689         d_advance (di, 2);
1690         return d_make_dtor (di, kind, di->last_name);
1691       }
1692
1693     default:
1694       return NULL;
1695     }
1696 }
1697
1698 /* <type> ::= <builtin-type>
1699           ::= <function-type>
1700           ::= <class-enum-type>
1701           ::= <array-type>
1702           ::= <pointer-to-member-type>
1703           ::= <template-param>
1704           ::= <template-template-param> <template-args>
1705           ::= <substitution>
1706           ::= <CV-qualifiers> <type>
1707           ::= P <type>
1708           ::= R <type>
1709           ::= C <type>
1710           ::= G <type>
1711           ::= U <source-name> <type>
1712
1713    <builtin-type> ::= various one letter codes
1714                   ::= u <source-name>
1715 */
1716
1717 CP_STATIC_IF_GLIBCPP_V3
1718 const struct demangle_builtin_type_info
1719 cplus_demangle_builtin_types[D_BUILTIN_TYPE_COUNT] =
1720 {
1721   /* a */ { NL ("signed char"), NL ("signed char"),     D_PRINT_DEFAULT },
1722   /* b */ { NL ("bool"),        NL ("boolean"),         D_PRINT_BOOL },
1723   /* c */ { NL ("char"),        NL ("byte"),            D_PRINT_DEFAULT },
1724   /* d */ { NL ("double"),      NL ("double"),          D_PRINT_FLOAT },
1725   /* e */ { NL ("long double"), NL ("long double"),     D_PRINT_FLOAT },
1726   /* f */ { NL ("float"),       NL ("float"),           D_PRINT_FLOAT },
1727   /* g */ { NL ("__float128"),  NL ("__float128"),      D_PRINT_FLOAT },
1728   /* h */ { NL ("unsigned char"), NL ("unsigned char"), D_PRINT_DEFAULT },
1729   /* i */ { NL ("int"),         NL ("int"),             D_PRINT_INT },
1730   /* j */ { NL ("unsigned int"), NL ("unsigned"),       D_PRINT_UNSIGNED },
1731   /* k */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1732   /* l */ { NL ("long"),        NL ("long"),            D_PRINT_LONG },
1733   /* m */ { NL ("unsigned long"), NL ("unsigned long"), D_PRINT_UNSIGNED_LONG },
1734   /* n */ { NL ("__int128"),    NL ("__int128"),        D_PRINT_DEFAULT },
1735   /* o */ { NL ("unsigned __int128"), NL ("unsigned __int128"),
1736             D_PRINT_DEFAULT },
1737   /* p */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1738   /* q */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1739   /* r */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1740   /* s */ { NL ("short"),       NL ("short"),           D_PRINT_DEFAULT },
1741   /* t */ { NL ("unsigned short"), NL ("unsigned short"), D_PRINT_DEFAULT },
1742   /* u */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1743   /* v */ { NL ("void"),        NL ("void"),            D_PRINT_VOID },
1744   /* w */ { NL ("wchar_t"),     NL ("char"),            D_PRINT_DEFAULT },
1745   /* x */ { NL ("long long"),   NL ("long"),            D_PRINT_LONG_LONG },
1746   /* y */ { NL ("unsigned long long"), NL ("unsigned long long"),
1747             D_PRINT_UNSIGNED_LONG_LONG },
1748   /* z */ { NL ("..."),         NL ("..."),             D_PRINT_DEFAULT },
1749 };
1750
1751 CP_STATIC_IF_GLIBCPP_V3
1752 struct demangle_component *
1753 cplus_demangle_type (struct d_info *di)
1754 {
1755   char peek;
1756   struct demangle_component *ret;
1757   int can_subst;
1758
1759   /* The ABI specifies that when CV-qualifiers are used, the base type
1760      is substitutable, and the fully qualified type is substitutable,
1761      but the base type with a strict subset of the CV-qualifiers is
1762      not substitutable.  The natural recursive implementation of the
1763      CV-qualifiers would cause subsets to be substitutable, so instead
1764      we pull them all off now.
1765
1766      FIXME: The ABI says that order-insensitive vendor qualifiers
1767      should be handled in the same way, but we have no way to tell
1768      which vendor qualifiers are order-insensitive and which are
1769      order-sensitive.  So we just assume that they are all
1770      order-sensitive.  g++ 3.4 supports only one vendor qualifier,
1771      __vector, and it treats it as order-sensitive when mangling
1772      names.  */
1773
1774   peek = d_peek_char (di);
1775   if (peek == 'r' || peek == 'V' || peek == 'K')
1776     {
1777       struct demangle_component **pret;
1778
1779       pret = d_cv_qualifiers (di, &ret, 0);
1780       if (pret == NULL)
1781         return NULL;
1782       *pret = cplus_demangle_type (di);
1783       if (! d_add_substitution (di, ret))
1784         return NULL;
1785       return ret;
1786     }
1787
1788   can_subst = 1;
1789
1790   switch (peek)
1791     {
1792     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1793     case 'h': case 'i': case 'j':           case 'l': case 'm': case 'n':
1794     case 'o':                               case 's': case 't':
1795     case 'v': case 'w': case 'x': case 'y': case 'z':
1796       ret = d_make_builtin_type (di,
1797                                  &cplus_demangle_builtin_types[peek - 'a']);
1798       di->expansion += ret->u.s_builtin.type->len;
1799       can_subst = 0;
1800       d_advance (di, 1);
1801       break;
1802
1803     case 'u':
1804       d_advance (di, 1);
1805       ret = d_make_comp (di, DEMANGLE_COMPONENT_VENDOR_TYPE,
1806                          d_source_name (di), NULL);
1807       break;
1808
1809     case 'F':
1810       ret = d_function_type (di);
1811       break;
1812
1813     case '0': case '1': case '2': case '3': case '4':
1814     case '5': case '6': case '7': case '8': case '9':
1815     case 'N':
1816     case 'Z':
1817       ret = d_class_enum_type (di);
1818       break;
1819
1820     case 'A':
1821       ret = d_array_type (di);
1822       break;
1823
1824     case 'M':
1825       ret = d_pointer_to_member_type (di);
1826       break;
1827
1828     case 'T':
1829       ret = d_template_param (di);
1830       if (d_peek_char (di) == 'I')
1831         {
1832           /* This is <template-template-param> <template-args>.  The
1833              <template-template-param> part is a substitution
1834              candidate.  */
1835           if (! d_add_substitution (di, ret))
1836             return NULL;
1837           ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
1838                              d_template_args (di));
1839         }
1840       break;
1841
1842     case 'S':
1843       /* If this is a special substitution, then it is the start of
1844          <class-enum-type>.  */
1845       {
1846         char peek_next;
1847
1848         peek_next = d_peek_next_char (di);
1849         if (IS_DIGIT (peek_next)
1850             || peek_next == '_'
1851             || IS_UPPER (peek_next))
1852           {
1853             ret = d_substitution (di, 0);
1854             /* The substituted name may have been a template name and
1855                may be followed by tepmlate args.  */
1856             if (d_peek_char (di) == 'I')
1857               ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
1858                                  d_template_args (di));
1859             else
1860               can_subst = 0;
1861           }
1862         else
1863           {
1864             ret = d_class_enum_type (di);
1865             /* If the substitution was a complete type, then it is not
1866                a new substitution candidate.  However, if the
1867                substitution was followed by template arguments, then
1868                the whole thing is a substitution candidate.  */
1869             if (ret != NULL && ret->type == DEMANGLE_COMPONENT_SUB_STD)
1870               can_subst = 0;
1871           }
1872       }
1873       break;
1874
1875     case 'P':
1876       d_advance (di, 1);
1877       ret = d_make_comp (di, DEMANGLE_COMPONENT_POINTER,
1878                          cplus_demangle_type (di), NULL);
1879       break;
1880
1881     case 'R':
1882       d_advance (di, 1);
1883       ret = d_make_comp (di, DEMANGLE_COMPONENT_REFERENCE,
1884                          cplus_demangle_type (di), NULL);
1885       break;
1886
1887     case 'C':
1888       d_advance (di, 1);
1889       ret = d_make_comp (di, DEMANGLE_COMPONENT_COMPLEX,
1890                          cplus_demangle_type (di), NULL);
1891       break;
1892
1893     case 'G':
1894       d_advance (di, 1);
1895       ret = d_make_comp (di, DEMANGLE_COMPONENT_IMAGINARY,
1896                          cplus_demangle_type (di), NULL);
1897       break;
1898
1899     case 'U':
1900       d_advance (di, 1);
1901       ret = d_source_name (di);
1902       ret = d_make_comp (di, DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL,
1903                          cplus_demangle_type (di), ret);
1904       break;
1905
1906     default:
1907       return NULL;
1908     }
1909
1910   if (can_subst)
1911     {
1912       if (! d_add_substitution (di, ret))
1913         return NULL;
1914     }
1915
1916   return ret;
1917 }
1918
1919 /* <CV-qualifiers> ::= [r] [V] [K]  */
1920
1921 static struct demangle_component **
1922 d_cv_qualifiers (struct d_info *di,
1923                  struct demangle_component **pret, int member_fn)
1924 {
1925   char peek;
1926
1927   peek = d_peek_char (di);
1928   while (peek == 'r' || peek == 'V' || peek == 'K')
1929     {
1930       enum demangle_component_type t;
1931
1932       d_advance (di, 1);
1933       if (peek == 'r')
1934         {
1935           t = (member_fn
1936                ? DEMANGLE_COMPONENT_RESTRICT_THIS
1937                : DEMANGLE_COMPONENT_RESTRICT);
1938           di->expansion += sizeof "restrict";
1939         }
1940       else if (peek == 'V')
1941         {
1942           t = (member_fn
1943                ? DEMANGLE_COMPONENT_VOLATILE_THIS
1944                : DEMANGLE_COMPONENT_VOLATILE);
1945           di->expansion += sizeof "volatile";
1946         }
1947       else
1948         {
1949           t = (member_fn
1950                ? DEMANGLE_COMPONENT_CONST_THIS
1951                : DEMANGLE_COMPONENT_CONST);
1952           di->expansion += sizeof "const";
1953         }
1954
1955       *pret = d_make_comp (di, t, NULL, NULL);
1956       if (*pret == NULL)
1957         return NULL;
1958       pret = &d_left (*pret);
1959
1960       peek = d_peek_char (di);
1961     }
1962
1963   return pret;
1964 }
1965
1966 /* <function-type> ::= F [Y] <bare-function-type> E  */
1967
1968 static struct demangle_component *
1969 d_function_type (struct d_info *di)
1970 {
1971   struct demangle_component *ret;
1972
1973   if (! d_check_char (di, 'F'))
1974     return NULL;
1975   if (d_peek_char (di) == 'Y')
1976     {
1977       /* Function has C linkage.  We don't print this information.
1978          FIXME: We should print it in verbose mode.  */
1979       d_advance (di, 1);
1980     }
1981   ret = d_bare_function_type (di, 1);
1982   if (! d_check_char (di, 'E'))
1983     return NULL;
1984   return ret;
1985 }
1986
1987 /* <bare-function-type> ::= [J]<type>+  */
1988
1989 static struct demangle_component *
1990 d_bare_function_type (struct d_info *di, int has_return_type)
1991 {
1992   struct demangle_component *return_type;
1993   struct demangle_component *tl;
1994   struct demangle_component **ptl;
1995   char peek;
1996
1997   /* Detect special qualifier indicating that the first argument
1998      is the return type.  */
1999   peek = d_peek_char (di);
2000   if (peek == 'J')
2001     {
2002       d_advance (di, 1);
2003       has_return_type = 1;
2004     }
2005
2006   return_type = NULL;
2007   tl = NULL;
2008   ptl = &tl;
2009   while (1)
2010     {
2011       struct demangle_component *type;
2012
2013       peek = d_peek_char (di);
2014       if (peek == '\0' || peek == 'E')
2015         break;
2016       type = cplus_demangle_type (di);
2017       if (type == NULL)
2018         return NULL;
2019       if (has_return_type)
2020         {
2021           return_type = type;
2022           has_return_type = 0;
2023         }
2024       else
2025         {
2026           *ptl = d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, type, NULL);
2027           if (*ptl == NULL)
2028             return NULL;
2029           ptl = &d_right (*ptl);
2030         }
2031     }
2032
2033   /* There should be at least one parameter type besides the optional
2034      return type.  A function which takes no arguments will have a
2035      single parameter type void.  */
2036   if (tl == NULL)
2037     return NULL;
2038
2039   /* If we have a single parameter type void, omit it.  */
2040   if (d_right (tl) == NULL
2041       && d_left (tl)->type == DEMANGLE_COMPONENT_BUILTIN_TYPE
2042       && d_left (tl)->u.s_builtin.type->print == D_PRINT_VOID)
2043     {
2044       di->expansion -= d_left (tl)->u.s_builtin.type->len;
2045       tl = NULL;
2046     }
2047
2048   return d_make_comp (di, DEMANGLE_COMPONENT_FUNCTION_TYPE, return_type, tl);
2049 }
2050
2051 /* <class-enum-type> ::= <name>  */
2052
2053 static struct demangle_component *
2054 d_class_enum_type (struct d_info *di)
2055 {
2056   return d_name (di);
2057 }
2058
2059 /* <array-type> ::= A <(positive dimension) number> _ <(element) type>
2060                 ::= A [<(dimension) expression>] _ <(element) type>
2061 */
2062
2063 static struct demangle_component *
2064 d_array_type (struct d_info *di)
2065 {
2066   char peek;
2067   struct demangle_component *dim;
2068
2069   if (! d_check_char (di, 'A'))
2070     return NULL;
2071
2072   peek = d_peek_char (di);
2073   if (peek == '_')
2074     dim = NULL;
2075   else if (IS_DIGIT (peek))
2076     {
2077       const char *s;
2078
2079       s = d_str (di);
2080       do
2081         {
2082           d_advance (di, 1);
2083           peek = d_peek_char (di);
2084         }
2085       while (IS_DIGIT (peek));
2086       dim = d_make_name (di, s, d_str (di) - s);
2087       if (dim == NULL)
2088         return NULL;
2089     }
2090   else
2091     {
2092       dim = d_expression (di);
2093       if (dim == NULL)
2094         return NULL;
2095     }
2096
2097   if (! d_check_char (di, '_'))
2098     return NULL;
2099
2100   return d_make_comp (di, DEMANGLE_COMPONENT_ARRAY_TYPE, dim,
2101                       cplus_demangle_type (di));
2102 }
2103
2104 /* <pointer-to-member-type> ::= M <(class) type> <(member) type>  */
2105
2106 static struct demangle_component *
2107 d_pointer_to_member_type (struct d_info *di)
2108 {
2109   struct demangle_component *cl;
2110   struct demangle_component *mem;
2111   struct demangle_component **pmem;
2112
2113   if (! d_check_char (di, 'M'))
2114     return NULL;
2115
2116   cl = cplus_demangle_type (di);
2117
2118   /* The ABI specifies that any type can be a substitution source, and
2119      that M is followed by two types, and that when a CV-qualified
2120      type is seen both the base type and the CV-qualified types are
2121      substitution sources.  The ABI also specifies that for a pointer
2122      to a CV-qualified member function, the qualifiers are attached to
2123      the second type.  Given the grammar, a plain reading of the ABI
2124      suggests that both the CV-qualified member function and the
2125      non-qualified member function are substitution sources.  However,
2126      g++ does not work that way.  g++ treats only the CV-qualified
2127      member function as a substitution source.  FIXME.  So to work
2128      with g++, we need to pull off the CV-qualifiers here, in order to
2129      avoid calling add_substitution() in cplus_demangle_type().  But
2130      for a CV-qualified member which is not a function, g++ does
2131      follow the ABI, so we need to handle that case here by calling
2132      d_add_substitution ourselves.  */
2133
2134   pmem = d_cv_qualifiers (di, &mem, 1);
2135   if (pmem == NULL)
2136     return NULL;
2137   *pmem = cplus_demangle_type (di);
2138
2139   if (pmem != &mem && (*pmem)->type != DEMANGLE_COMPONENT_FUNCTION_TYPE)
2140     {
2141       if (! d_add_substitution (di, mem))
2142         return NULL;
2143     }
2144
2145   return d_make_comp (di, DEMANGLE_COMPONENT_PTRMEM_TYPE, cl, mem);
2146 }
2147
2148 /* <template-param> ::= T_
2149                     ::= T <(parameter-2 non-negative) number> _
2150 */
2151
2152 static struct demangle_component *
2153 d_template_param (struct d_info *di)
2154 {
2155   long param;
2156
2157   if (! d_check_char (di, 'T'))
2158     return NULL;
2159
2160   if (d_peek_char (di) == '_')
2161     param = 0;
2162   else
2163     {
2164       param = d_number (di);
2165       if (param < 0)
2166         return NULL;
2167       param += 1;
2168     }
2169
2170   if (! d_check_char (di, '_'))
2171     return NULL;
2172
2173   ++di->did_subs;
2174
2175   return d_make_template_param (di, param);
2176 }
2177
2178 /* <template-args> ::= I <template-arg>+ E  */
2179
2180 static struct demangle_component *
2181 d_template_args (struct d_info *di)
2182 {
2183   struct demangle_component *hold_last_name;
2184   struct demangle_component *al;
2185   struct demangle_component **pal;
2186
2187   /* Preserve the last name we saw--don't let the template arguments
2188      clobber it, as that would give us the wrong name for a subsequent
2189      constructor or destructor.  */
2190   hold_last_name = di->last_name;
2191
2192   if (! d_check_char (di, 'I'))
2193     return NULL;
2194
2195   al = NULL;
2196   pal = &al;
2197   while (1)
2198     {
2199       struct demangle_component *a;
2200
2201       a = d_template_arg (di);
2202       if (a == NULL)
2203         return NULL;
2204
2205       *pal = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE_ARGLIST, a, NULL);
2206       if (*pal == NULL)
2207         return NULL;
2208       pal = &d_right (*pal);
2209
2210       if (d_peek_char (di) == 'E')
2211         {
2212           d_advance (di, 1);
2213           break;
2214         }
2215     }
2216
2217   di->last_name = hold_last_name;
2218
2219   return al;
2220 }
2221
2222 /* <template-arg> ::= <type>
2223                   ::= X <expression> E
2224                   ::= <expr-primary>
2225 */
2226
2227 static struct demangle_component *
2228 d_template_arg (struct d_info *di)
2229 {
2230   struct demangle_component *ret;
2231
2232   switch (d_peek_char (di))
2233     {
2234     case 'X':
2235       d_advance (di, 1);
2236       ret = d_expression (di);
2237       if (! d_check_char (di, 'E'))
2238         return NULL;
2239       return ret;
2240
2241     case 'L':
2242       return d_expr_primary (di);
2243
2244     default:
2245       return cplus_demangle_type (di);
2246     }
2247 }
2248
2249 /* <expression> ::= <(unary) operator-name> <expression>
2250                 ::= <(binary) operator-name> <expression> <expression>
2251                 ::= <(trinary) operator-name> <expression> <expression> <expression>
2252                 ::= st <type>
2253                 ::= <template-param>
2254                 ::= sr <type> <unqualified-name>
2255                 ::= sr <type> <unqualified-name> <template-args>
2256                 ::= <expr-primary>
2257 */
2258
2259 static struct demangle_component *
2260 d_expression (struct d_info *di)
2261 {
2262   char peek;
2263
2264   peek = d_peek_char (di);
2265   if (peek == 'L')
2266     return d_expr_primary (di);
2267   else if (peek == 'T')
2268     return d_template_param (di);
2269   else if (peek == 's' && d_peek_next_char (di) == 'r')
2270     {
2271       struct demangle_component *type;
2272       struct demangle_component *name;
2273
2274       d_advance (di, 2);
2275       type = cplus_demangle_type (di);
2276       name = d_unqualified_name (di);
2277       if (d_peek_char (di) != 'I')
2278         return d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME, type, name);
2279       else
2280         return d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME, type,
2281                             d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, name,
2282                                          d_template_args (di)));
2283     }
2284   else
2285     {
2286       struct demangle_component *op;
2287       int args;
2288
2289       op = d_operator_name (di);
2290       if (op == NULL)
2291         return NULL;
2292
2293       if (op->type == DEMANGLE_COMPONENT_OPERATOR)
2294         di->expansion += op->u.s_operator.op->len - 2;
2295
2296       if (op->type == DEMANGLE_COMPONENT_OPERATOR
2297           && strcmp (op->u.s_operator.op->code, "st") == 0)
2298         return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
2299                             cplus_demangle_type (di));
2300
2301       switch (op->type)
2302         {
2303         default:
2304           return NULL;
2305         case DEMANGLE_COMPONENT_OPERATOR:
2306           args = op->u.s_operator.op->args;
2307           break;
2308         case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
2309           args = op->u.s_extended_operator.args;
2310           break;
2311         case DEMANGLE_COMPONENT_CAST:
2312           args = 1;
2313           break;
2314         }
2315
2316       switch (args)
2317         {
2318         case 1:
2319           return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
2320                               d_expression (di));
2321         case 2:
2322           {
2323             struct demangle_component *left;
2324
2325             left = d_expression (di);
2326             return d_make_comp (di, DEMANGLE_COMPONENT_BINARY, op,
2327                                 d_make_comp (di,
2328                                              DEMANGLE_COMPONENT_BINARY_ARGS,
2329                                              left,
2330                                              d_expression (di)));
2331           }
2332         case 3:
2333           {
2334             struct demangle_component *first;
2335             struct demangle_component *second;
2336
2337             first = d_expression (di);
2338             second = d_expression (di);
2339             return d_make_comp (di, DEMANGLE_COMPONENT_TRINARY, op,
2340                                 d_make_comp (di,
2341                                              DEMANGLE_COMPONENT_TRINARY_ARG1,
2342                                              first,
2343                                              d_make_comp (di,
2344                                                           DEMANGLE_COMPONENT_TRINARY_ARG2,
2345                                                           second,
2346                                                           d_expression (di))));
2347           }
2348         default:
2349           return NULL;
2350         }
2351     }
2352 }
2353
2354 /* <expr-primary> ::= L <type> <(value) number> E
2355                   ::= L <type> <(value) float> E
2356                   ::= L <mangled-name> E
2357 */
2358
2359 static struct demangle_component *
2360 d_expr_primary (struct d_info *di)
2361 {
2362   struct demangle_component *ret;
2363
2364   if (! d_check_char (di, 'L'))
2365     return NULL;
2366   if (d_peek_char (di) == '_')
2367     ret = cplus_demangle_mangled_name (di, 0);
2368   else
2369     {
2370       struct demangle_component *type;
2371       enum demangle_component_type t;
2372       const char *s;
2373
2374       type = cplus_demangle_type (di);
2375       if (type == NULL)
2376         return NULL;
2377
2378       /* If we have a type we know how to print, we aren't going to
2379          print the type name itself.  */
2380       if (type->type == DEMANGLE_COMPONENT_BUILTIN_TYPE
2381           && type->u.s_builtin.type->print != D_PRINT_DEFAULT)
2382         di->expansion -= type->u.s_builtin.type->len;
2383
2384       /* Rather than try to interpret the literal value, we just
2385          collect it as a string.  Note that it's possible to have a
2386          floating point literal here.  The ABI specifies that the
2387          format of such literals is machine independent.  That's fine,
2388          but what's not fine is that versions of g++ up to 3.2 with
2389          -fabi-version=1 used upper case letters in the hex constant,
2390          and dumped out gcc's internal representation.  That makes it
2391          hard to tell where the constant ends, and hard to dump the
2392          constant in any readable form anyhow.  We don't attempt to
2393          handle these cases.  */
2394
2395       t = DEMANGLE_COMPONENT_LITERAL;
2396       if (d_peek_char (di) == 'n')
2397         {
2398           t = DEMANGLE_COMPONENT_LITERAL_NEG;
2399           d_advance (di, 1);
2400         }
2401       s = d_str (di);
2402       while (d_peek_char (di) != 'E')
2403         {
2404           if (d_peek_char (di) == '\0')
2405             return NULL;
2406           d_advance (di, 1);
2407         }
2408       ret = d_make_comp (di, t, type, d_make_name (di, s, d_str (di) - s));
2409     }
2410   if (! d_check_char (di, 'E'))
2411     return NULL;
2412   return ret;
2413 }
2414
2415 /* <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
2416                 ::= Z <(function) encoding> E s [<discriminator>]
2417 */
2418
2419 static struct demangle_component *
2420 d_local_name (struct d_info *di)
2421 {
2422   struct demangle_component *function;
2423
2424   if (! d_check_char (di, 'Z'))
2425     return NULL;
2426
2427   function = d_encoding (di, 0);
2428
2429   if (! d_check_char (di, 'E'))
2430     return NULL;
2431
2432   if (d_peek_char (di) == 's')
2433     {
2434       d_advance (di, 1);
2435       if (! d_discriminator (di))
2436         return NULL;
2437       return d_make_comp (di, DEMANGLE_COMPONENT_LOCAL_NAME, function,
2438                           d_make_name (di, "string literal",
2439                                        sizeof "string literal" - 1));
2440     }
2441   else
2442     {
2443       struct demangle_component *name;
2444
2445       name = d_name (di);
2446       if (! d_discriminator (di))
2447         return NULL;
2448       return d_make_comp (di, DEMANGLE_COMPONENT_LOCAL_NAME, function, name);
2449     }
2450 }
2451
2452 /* <discriminator> ::= _ <(non-negative) number>
2453
2454    We demangle the discriminator, but we don't print it out.  FIXME:
2455    We should print it out in verbose mode.  */
2456
2457 static int
2458 d_discriminator (struct d_info *di)
2459 {
2460   long discrim;
2461
2462   if (d_peek_char (di) != '_')
2463     return 1;
2464   d_advance (di, 1);
2465   discrim = d_number (di);
2466   if (discrim < 0)
2467     return 0;
2468   return 1;
2469 }
2470
2471 /* Add a new substitution.  */
2472
2473 static int
2474 d_add_substitution (struct d_info *di, struct demangle_component *dc)
2475 {
2476   if (dc == NULL)
2477     return 0;
2478   if (di->next_sub >= di->num_subs)
2479     return 0;
2480   di->subs[di->next_sub] = dc;
2481   ++di->next_sub;
2482   return 1;
2483 }
2484
2485 /* <substitution> ::= S <seq-id> _
2486                   ::= S_
2487                   ::= St
2488                   ::= Sa
2489                   ::= Sb
2490                   ::= Ss
2491                   ::= Si
2492                   ::= So
2493                   ::= Sd
2494
2495    If PREFIX is non-zero, then this type is being used as a prefix in
2496    a qualified name.  In this case, for the standard substitutions, we
2497    need to check whether we are being used as a prefix for a
2498    constructor or destructor, and return a full template name.
2499    Otherwise we will get something like std::iostream::~iostream()
2500    which does not correspond particularly well to any function which
2501    actually appears in the source.
2502 */
2503
2504 static const struct d_standard_sub_info standard_subs[] =
2505 {
2506   { 't', NL ("std"),
2507     NL ("std"),
2508     NULL, 0 },
2509   { 'a', NL ("std::allocator"),
2510     NL ("std::allocator"),
2511     NL ("allocator") },
2512   { 'b', NL ("std::basic_string"),
2513     NL ("std::basic_string"),
2514     NL ("basic_string") },
2515   { 's', NL ("std::string"),
2516     NL ("std::basic_string<char, std::char_traits<char>, std::allocator<char> >"),
2517     NL ("basic_string") },
2518   { 'i', NL ("std::istream"),
2519     NL ("std::basic_istream<char, std::char_traits<char> >"),
2520     NL ("basic_istream") },
2521   { 'o', NL ("std::ostream"),
2522     NL ("std::basic_ostream<char, std::char_traits<char> >"),
2523     NL ("basic_ostream") },
2524   { 'd', NL ("std::iostream"),
2525     NL ("std::basic_iostream<char, std::char_traits<char> >"),
2526     NL ("basic_iostream") }
2527 };
2528
2529 static struct demangle_component *
2530 d_substitution (struct d_info *di, int prefix)
2531 {
2532   char c;
2533
2534   if (! d_check_char (di, 'S'))
2535     return NULL;
2536
2537   c = d_next_char (di);
2538   if (c == '_' || IS_DIGIT (c) || IS_UPPER (c))
2539     {
2540       int id;
2541
2542       id = 0;
2543       if (c != '_')
2544         {
2545           do
2546             {
2547               if (IS_DIGIT (c))
2548                 id = id * 36 + c - '0';
2549               else if (IS_UPPER (c))
2550                 id = id * 36 + c - 'A' + 10;
2551               else
2552                 return NULL;
2553               if (id < 0)
2554                 return NULL;
2555               c = d_next_char (di);
2556             }
2557           while (c != '_');
2558
2559           ++id;
2560         }
2561
2562       if (id >= di->next_sub)
2563         return NULL;
2564
2565       ++di->did_subs;
2566
2567       return di->subs[id];
2568     }
2569   else
2570     {
2571       int verbose;
2572       const struct d_standard_sub_info *p;
2573       const struct d_standard_sub_info *pend;
2574
2575       verbose = (di->options & DMGL_VERBOSE) != 0;
2576       if (! verbose && prefix)
2577         {
2578           char peek;
2579
2580           peek = d_peek_char (di);
2581           if (peek == 'C' || peek == 'D')
2582             verbose = 1;
2583         }
2584
2585       pend = (&standard_subs[0]
2586               + sizeof standard_subs / sizeof standard_subs[0]);
2587       for (p = &standard_subs[0]; p < pend; ++p)
2588         {
2589           if (c == p->code)
2590             {
2591               const char *s;
2592               int len;
2593
2594               if (p->set_last_name != NULL)
2595                 di->last_name = d_make_sub (di, p->set_last_name,
2596                                             p->set_last_name_len);
2597               if (verbose)
2598                 {
2599                   s = p->full_expansion;
2600                   len = p->full_len;
2601                 }
2602               else
2603                 {
2604                   s = p->simple_expansion;
2605                   len = p->simple_len;
2606                 }
2607               di->expansion += len;
2608               return d_make_sub (di, s, len);
2609             }
2610         }
2611
2612       return NULL;
2613     }
2614 }
2615
2616 /* Initialize a growable string.  */
2617
2618 static void
2619 d_growable_string_init (struct d_growable_string *dgs, size_t estimate)
2620 {
2621   dgs->buf = NULL;
2622   dgs->len = 0;
2623   dgs->alc = 0;
2624   dgs->allocation_failure = 0;
2625
2626   if (estimate > 0)
2627     d_growable_string_resize (dgs, estimate);
2628 }
2629
2630 /* Grow a growable string to a given size.  */
2631
2632 static inline void
2633 d_growable_string_resize (struct d_growable_string *dgs, size_t need)
2634 {
2635   size_t newalc;
2636   char *newbuf;
2637
2638   if (dgs->allocation_failure)
2639     return;
2640
2641   /* Start allocation at two bytes to avoid any possibility of confusion
2642      with the special value of 1 used as a return in *palc to indicate
2643      allocation failures.  */
2644   newalc = dgs->alc > 0 ? dgs->alc : 2;
2645   while (newalc < need)
2646     newalc <<= 1;
2647
2648   newbuf = (char *) realloc (dgs->buf, newalc);
2649   if (newbuf == NULL)
2650     {
2651       free (dgs->buf);
2652       dgs->buf = NULL;
2653       dgs->len = 0;
2654       dgs->alc = 0;
2655       dgs->allocation_failure = 1;
2656       return;
2657     }
2658   dgs->buf = newbuf;
2659   dgs->alc = newalc;
2660 }
2661
2662 /* Append a buffer to a growable string.  */
2663
2664 static inline void
2665 d_growable_string_append_buffer (struct d_growable_string *dgs,
2666                                  const char *s, size_t l)
2667 {
2668   size_t need;
2669
2670   need = dgs->len + l + 1;
2671   if (need > dgs->alc)
2672     d_growable_string_resize (dgs, need);
2673
2674   if (dgs->allocation_failure)
2675     return;
2676
2677   memcpy (dgs->buf + dgs->len, s, l);
2678   dgs->buf[dgs->len + l] = '\0';
2679   dgs->len += l;
2680 }
2681
2682 /* Bridge growable strings to the callback mechanism.  */
2683
2684 static void
2685 d_growable_string_callback_adapter (const char *s, size_t l, void *opaque)
2686 {
2687   struct d_growable_string *dgs = (struct d_growable_string*) opaque;
2688
2689   d_growable_string_append_buffer (dgs, s, l);
2690 }
2691
2692 /* Initialize a print information structure.  */
2693
2694 static void
2695 d_print_init (struct d_print_info *dpi, int options,
2696               demangle_callbackref callback, void *opaque)
2697 {
2698   dpi->options = options;
2699   dpi->len = 0;
2700   dpi->last_char = '\0';
2701   dpi->templates = NULL;
2702   dpi->modifiers = NULL;
2703
2704   dpi->callback = callback;
2705   dpi->opaque = opaque;
2706
2707   dpi->demangle_failure = 0;
2708 }
2709
2710 /* Indicate that an error occurred during printing, and test for error.  */
2711
2712 static inline void
2713 d_print_error (struct d_print_info *dpi)
2714 {
2715   dpi->demangle_failure = 1;
2716 }
2717
2718 static inline int
2719 d_print_saw_error (struct d_print_info *dpi)
2720 {
2721   return dpi->demangle_failure != 0;
2722 }
2723
2724 /* Flush buffered characters to the callback.  */
2725
2726 static inline void
2727 d_print_flush (struct d_print_info *dpi)
2728 {
2729   dpi->buf[dpi->len] = '\0';
2730   dpi->callback (dpi->buf, dpi->len, dpi->opaque);
2731   dpi->len = 0;
2732 }
2733
2734 /* Append characters and buffers for printing.  */
2735
2736 static inline void
2737 d_append_char (struct d_print_info *dpi, char c)
2738 {
2739   if (dpi->len == sizeof (dpi->buf) - 1)
2740     d_print_flush (dpi);
2741
2742   dpi->buf[dpi->len++] = c;
2743   dpi->last_char = c;
2744 }
2745
2746 static inline void
2747 d_append_buffer (struct d_print_info *dpi, const char *s, size_t l)
2748 {
2749   size_t i;
2750
2751   for (i = 0; i < l; i++)
2752     d_append_char (dpi, s[i]);
2753 }
2754
2755 static inline void
2756 d_append_string (struct d_print_info *dpi, const char *s)
2757 {
2758   d_append_buffer (dpi, s, strlen (s));
2759 }
2760
2761 static inline char
2762 d_last_char (struct d_print_info *dpi)
2763 {
2764   return dpi->last_char;
2765 }
2766
2767 /* Turn components into a human readable string.  OPTIONS is the
2768    options bits passed to the demangler.  DC is the tree to print.
2769    CALLBACK is a function to call to flush demangled string segments
2770    as they fill the intermediate buffer, and OPAQUE is a generalized
2771    callback argument.  On success, this returns 1.  On failure,
2772    it returns 0, indicating a bad parse.  It does not use heap
2773    memory to build an output string, so cannot encounter memory
2774    allocation failure.  */
2775
2776 CP_STATIC_IF_GLIBCPP_V3
2777 int
2778 cplus_demangle_print_callback (int options,
2779                                const struct demangle_component *dc,
2780                                demangle_callbackref callback, void *opaque)
2781 {
2782   struct d_print_info dpi;
2783
2784   d_print_init (&dpi, options, callback, opaque);
2785
2786   d_print_comp (&dpi, dc);
2787
2788   d_print_flush (&dpi);
2789
2790   return ! d_print_saw_error (&dpi);
2791 }
2792
2793 /* Turn components into a human readable string.  OPTIONS is the
2794    options bits passed to the demangler.  DC is the tree to print.
2795    ESTIMATE is a guess at the length of the result.  This returns a
2796    string allocated by malloc, or NULL on error.  On success, this
2797    sets *PALC to the size of the allocated buffer.  On failure, this
2798    sets *PALC to 0 for a bad parse, or to 1 for a memory allocation
2799    failure.  */
2800
2801 CP_STATIC_IF_GLIBCPP_V3
2802 char *
2803 cplus_demangle_print (int options, const struct demangle_component *dc,
2804                       int estimate, size_t *palc)
2805 {
2806   struct d_growable_string dgs;
2807
2808   d_growable_string_init (&dgs, estimate);
2809
2810   if (! cplus_demangle_print_callback (options, dc,
2811                                        d_growable_string_callback_adapter,
2812                                        &dgs))
2813     {
2814       free (dgs.buf);
2815       *palc = 0;
2816       return NULL;
2817     }
2818
2819   *palc = dgs.allocation_failure ? 1 : dgs.alc;
2820   return dgs.buf;
2821 }
2822
2823 /* Subroutine to handle components.  */
2824
2825 static void
2826 d_print_comp (struct d_print_info *dpi,
2827               const struct demangle_component *dc)
2828 {
2829   if (dc == NULL)
2830     {
2831       d_print_error (dpi);
2832       return;
2833     }
2834   if (d_print_saw_error (dpi))
2835     return;
2836
2837   switch (dc->type)
2838     {
2839     case DEMANGLE_COMPONENT_NAME:
2840       if ((dpi->options & DMGL_JAVA) == 0)
2841         d_append_buffer (dpi, dc->u.s_name.s, dc->u.s_name.len);
2842       else
2843         d_print_java_identifier (dpi, dc->u.s_name.s, dc->u.s_name.len);
2844       return;
2845
2846     case DEMANGLE_COMPONENT_QUAL_NAME:
2847     case DEMANGLE_COMPONENT_LOCAL_NAME:
2848       d_print_comp (dpi, d_left (dc));
2849       if ((dpi->options & DMGL_JAVA) == 0)
2850         d_append_string (dpi, "::");
2851       else
2852         d_append_char (dpi, '.');
2853       d_print_comp (dpi, d_right (dc));
2854       return;
2855
2856     case DEMANGLE_COMPONENT_TYPED_NAME:
2857       {
2858         struct d_print_mod *hold_modifiers;
2859         struct demangle_component *typed_name;
2860         struct d_print_mod adpm[4];
2861         unsigned int i;
2862         struct d_print_template dpt;
2863
2864         /* Pass the name down to the type so that it can be printed in
2865            the right place for the type.  We also have to pass down
2866            any CV-qualifiers, which apply to the this parameter.  */
2867         hold_modifiers = dpi->modifiers;
2868         i = 0;
2869         typed_name = d_left (dc);
2870         while (typed_name != NULL)
2871           {
2872             if (i >= sizeof adpm / sizeof adpm[0])
2873               {
2874                 d_print_error (dpi);
2875                 return;
2876               }
2877
2878             adpm[i].next = dpi->modifiers;
2879             dpi->modifiers = &adpm[i];
2880             adpm[i].mod = typed_name;
2881             adpm[i].printed = 0;
2882             adpm[i].templates = dpi->templates;
2883             ++i;
2884
2885             if (typed_name->type != DEMANGLE_COMPONENT_RESTRICT_THIS
2886                 && typed_name->type != DEMANGLE_COMPONENT_VOLATILE_THIS
2887                 && typed_name->type != DEMANGLE_COMPONENT_CONST_THIS)
2888               break;
2889
2890             typed_name = d_left (typed_name);
2891           }
2892
2893         /* If typed_name is a template, then it applies to the
2894            function type as well.  */
2895         if (typed_name->type == DEMANGLE_COMPONENT_TEMPLATE)
2896           {
2897             dpt.next = dpi->templates;
2898             dpi->templates = &dpt;
2899             dpt.template_decl = typed_name;
2900           }
2901
2902         /* If typed_name is a DEMANGLE_COMPONENT_LOCAL_NAME, then
2903            there may be CV-qualifiers on its right argument which
2904            really apply here; this happens when parsing a class which
2905            is local to a function.  */
2906         if (typed_name->type == DEMANGLE_COMPONENT_LOCAL_NAME)
2907           {
2908             struct demangle_component *local_name;
2909
2910             local_name = d_right (typed_name);
2911             while (local_name->type == DEMANGLE_COMPONENT_RESTRICT_THIS
2912                    || local_name->type == DEMANGLE_COMPONENT_VOLATILE_THIS
2913                    || local_name->type == DEMANGLE_COMPONENT_CONST_THIS)
2914               {
2915                 if (i >= sizeof adpm / sizeof adpm[0])
2916                   {
2917                     d_print_error (dpi);
2918                     return;
2919                   }
2920
2921                 adpm[i] = adpm[i - 1];
2922                 adpm[i].next = &adpm[i - 1];
2923                 dpi->modifiers = &adpm[i];
2924
2925                 adpm[i - 1].mod = local_name;
2926                 adpm[i - 1].printed = 0;
2927                 adpm[i - 1].templates = dpi->templates;
2928                 ++i;
2929
2930                 local_name = d_left (local_name);
2931               }
2932           }
2933
2934         d_print_comp (dpi, d_right (dc));
2935
2936         if (typed_name->type == DEMANGLE_COMPONENT_TEMPLATE)
2937           dpi->templates = dpt.next;
2938
2939         /* If the modifiers didn't get printed by the type, print them
2940            now.  */
2941         while (i > 0)
2942           {
2943             --i;
2944             if (! adpm[i].printed)
2945               {
2946                 d_append_char (dpi, ' ');
2947                 d_print_mod (dpi, adpm[i].mod);
2948               }
2949           }
2950
2951         dpi->modifiers = hold_modifiers;
2952
2953         return;
2954       }
2955
2956     case DEMANGLE_COMPONENT_TEMPLATE:
2957       {
2958         struct d_print_mod *hold_dpm;
2959         struct demangle_component *dcl;
2960
2961         /* Don't push modifiers into a template definition.  Doing so
2962            could give the wrong definition for a template argument.
2963            Instead, treat the template essentially as a name.  */
2964
2965         hold_dpm = dpi->modifiers;
2966         dpi->modifiers = NULL;
2967
2968         dcl = d_left (dc);
2969
2970         if ((dpi->options & DMGL_JAVA) != 0
2971             && dcl->type == DEMANGLE_COMPONENT_NAME
2972             && dcl->u.s_name.len == 6
2973             && strncmp (dcl->u.s_name.s, "JArray", 6) == 0)
2974           {
2975             /* Special-case Java arrays, so that JArray<TYPE> appears
2976                instead as TYPE[].  */
2977
2978             d_print_comp (dpi, d_right (dc));
2979             d_append_string (dpi, "[]");
2980           }
2981         else
2982           {
2983             d_print_comp (dpi, dcl);
2984             if (d_last_char (dpi) == '<')
2985               d_append_char (dpi, ' ');
2986             d_append_char (dpi, '<');
2987             d_print_comp (dpi, d_right (dc));
2988             /* Avoid generating two consecutive '>' characters, to avoid
2989                the C++ syntactic ambiguity.  */
2990             if (d_last_char (dpi) == '>')
2991               d_append_char (dpi, ' ');
2992             d_append_char (dpi, '>');
2993           }
2994
2995         dpi->modifiers = hold_dpm;
2996
2997         return;
2998       }
2999
3000     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
3001       {
3002         long i;
3003         struct demangle_component *a;
3004         struct d_print_template *hold_dpt;
3005
3006         if (dpi->templates == NULL)
3007           {
3008             d_print_error (dpi);
3009             return;
3010           }
3011         i = dc->u.s_number.number;
3012         for (a = d_right (dpi->templates->template_decl);
3013              a != NULL;
3014              a = d_right (a))
3015           {
3016             if (a->type != DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
3017               {
3018                 d_print_error (dpi);
3019                 return;
3020               }
3021             if (i <= 0)
3022               break;
3023             --i;
3024           }
3025         if (i != 0 || a == NULL)
3026           {
3027             d_print_error (dpi);
3028             return;
3029           }
3030
3031         /* While processing this parameter, we need to pop the list of
3032            templates.  This is because the template parameter may
3033            itself be a reference to a parameter of an outer
3034            template.  */
3035
3036         hold_dpt = dpi->templates;
3037         dpi->templates = hold_dpt->next;
3038
3039         d_print_comp (dpi, d_left (a));
3040
3041         dpi->templates = hold_dpt;
3042
3043         return;
3044       }
3045
3046     case DEMANGLE_COMPONENT_CTOR:
3047       d_print_comp (dpi, dc->u.s_ctor.name);
3048       return;
3049
3050     case DEMANGLE_COMPONENT_DTOR:
3051       d_append_char (dpi, '~');
3052       d_print_comp (dpi, dc->u.s_dtor.name);
3053       return;
3054
3055     case DEMANGLE_COMPONENT_VTABLE:
3056       d_append_string (dpi, "vtable for ");
3057       d_print_comp (dpi, d_left (dc));
3058       return;
3059
3060     case DEMANGLE_COMPONENT_VTT:
3061       d_append_string (dpi, "VTT for ");
3062       d_print_comp (dpi, d_left (dc));
3063       return;
3064
3065     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
3066       d_append_string (dpi, "construction vtable for ");
3067       d_print_comp (dpi, d_left (dc));
3068       d_append_string (dpi, "-in-");
3069       d_print_comp (dpi, d_right (dc));
3070       return;
3071
3072     case DEMANGLE_COMPONENT_TYPEINFO:
3073       d_append_string (dpi, "typeinfo for ");
3074       d_print_comp (dpi, d_left (dc));
3075       return;
3076
3077     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
3078       d_append_string (dpi, "typeinfo name for ");
3079       d_print_comp (dpi, d_left (dc));
3080       return;
3081
3082     case DEMANGLE_COMPONENT_TYPEINFO_FN:
3083       d_append_string (dpi, "typeinfo fn for ");
3084       d_print_comp (dpi, d_left (dc));
3085       return;
3086
3087     case DEMANGLE_COMPONENT_THUNK:
3088       d_append_string (dpi, "non-virtual thunk to ");
3089       d_print_comp (dpi, d_left (dc));
3090       return;
3091
3092     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
3093       d_append_string (dpi, "virtual thunk to ");
3094       d_print_comp (dpi, d_left (dc));
3095       return;
3096
3097     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
3098       d_append_string (dpi, "covariant return thunk to ");
3099       d_print_comp (dpi, d_left (dc));
3100       return;
3101
3102     case DEMANGLE_COMPONENT_JAVA_CLASS:
3103       d_append_string (dpi, "java Class for ");
3104       d_print_comp (dpi, d_left (dc));
3105       return;
3106
3107     case DEMANGLE_COMPONENT_GUARD:
3108       d_append_string (dpi, "guard variable for ");
3109       d_print_comp (dpi, d_left (dc));
3110       return;
3111
3112     case DEMANGLE_COMPONENT_REFTEMP:
3113       d_append_string (dpi, "reference temporary for ");
3114       d_print_comp (dpi, d_left (dc));
3115       return;
3116
3117     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
3118       d_append_string (dpi, "hidden alias for ");
3119       d_print_comp (dpi, d_left (dc));
3120       return;
3121
3122     case DEMANGLE_COMPONENT_SUB_STD:
3123       d_append_buffer (dpi, dc->u.s_string.string, dc->u.s_string.len);
3124       return;
3125
3126     case DEMANGLE_COMPONENT_RESTRICT:
3127     case DEMANGLE_COMPONENT_VOLATILE:
3128     case DEMANGLE_COMPONENT_CONST:
3129       {
3130         struct d_print_mod *pdpm;
3131
3132         /* When printing arrays, it's possible to have cases where the
3133            same CV-qualifier gets pushed on the stack multiple times.
3134            We only need to print it once.  */
3135
3136         for (pdpm = dpi->modifiers; pdpm != NULL; pdpm = pdpm->next)
3137           {
3138             if (! pdpm->printed)
3139               {
3140                 if (pdpm->mod->type != DEMANGLE_COMPONENT_RESTRICT
3141                     && pdpm->mod->type != DEMANGLE_COMPONENT_VOLATILE
3142                     && pdpm->mod->type != DEMANGLE_COMPONENT_CONST)
3143                   break;
3144                 if (pdpm->mod->type == dc->type)
3145                   {
3146                     d_print_comp (dpi, d_left (dc));
3147                     return;
3148                   }
3149               }
3150           }
3151       }
3152       /* Fall through.  */
3153     case DEMANGLE_COMPONENT_RESTRICT_THIS:
3154     case DEMANGLE_COMPONENT_VOLATILE_THIS:
3155     case DEMANGLE_COMPONENT_CONST_THIS:
3156     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
3157     case DEMANGLE_COMPONENT_POINTER:
3158     case DEMANGLE_COMPONENT_REFERENCE:
3159     case DEMANGLE_COMPONENT_COMPLEX:
3160     case DEMANGLE_COMPONENT_IMAGINARY:
3161       {
3162         /* We keep a list of modifiers on the stack.  */
3163         struct d_print_mod dpm;
3164
3165         dpm.next = dpi->modifiers;
3166         dpi->modifiers = &dpm;
3167         dpm.mod = dc;
3168         dpm.printed = 0;
3169         dpm.templates = dpi->templates;
3170
3171         d_print_comp (dpi, d_left (dc));
3172
3173         /* If the modifier didn't get printed by the type, print it
3174            now.  */
3175         if (! dpm.printed)
3176           d_print_mod (dpi, dc);
3177
3178         dpi->modifiers = dpm.next;
3179
3180         return;
3181       }
3182
3183     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
3184       if ((dpi->options & DMGL_JAVA) == 0)
3185         d_append_buffer (dpi, dc->u.s_builtin.type->name,
3186                          dc->u.s_builtin.type->len);
3187       else
3188         d_append_buffer (dpi, dc->u.s_builtin.type->java_name,
3189                          dc->u.s_builtin.type->java_len);
3190       return;
3191
3192     case DEMANGLE_COMPONENT_VENDOR_TYPE:
3193       d_print_comp (dpi, d_left (dc));
3194       return;
3195
3196     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
3197       {
3198         if ((dpi->options & DMGL_RET_POSTFIX) != 0)
3199           d_print_function_type (dpi, dc, dpi->modifiers);
3200
3201         /* Print return type if present */
3202         if (d_left (dc) != NULL)
3203           {
3204             struct d_print_mod dpm;
3205
3206             /* We must pass this type down as a modifier in order to
3207                print it in the right location.  */
3208             dpm.next = dpi->modifiers;
3209             dpi->modifiers = &dpm;
3210             dpm.mod = dc;
3211             dpm.printed = 0;
3212             dpm.templates = dpi->templates;
3213
3214             d_print_comp (dpi, d_left (dc));
3215
3216             dpi->modifiers = dpm.next;
3217
3218             if (dpm.printed)
3219               return;
3220
3221             /* In standard prefix notation, there is a space between the
3222                return type and the function signature.  */
3223             if ((dpi->options & DMGL_RET_POSTFIX) == 0)
3224               d_append_char (dpi, ' ');
3225           }
3226
3227         if ((dpi->options & DMGL_RET_POSTFIX) == 0) 
3228           d_print_function_type (dpi, dc, dpi->modifiers);
3229
3230         return;
3231       }
3232
3233     case DEMANGLE_COMPONENT_ARRAY_TYPE:
3234       {
3235         struct d_print_mod *hold_modifiers;
3236         struct d_print_mod adpm[4];
3237         unsigned int i;
3238         struct d_print_mod *pdpm;
3239
3240         /* We must pass this type down as a modifier in order to print
3241            multi-dimensional arrays correctly.  If the array itself is
3242            CV-qualified, we act as though the element type were
3243            CV-qualified.  We do this by copying the modifiers down
3244            rather than fiddling pointers, so that we don't wind up
3245            with a d_print_mod higher on the stack pointing into our
3246            stack frame after we return.  */
3247
3248         hold_modifiers = dpi->modifiers;
3249
3250         adpm[0].next = hold_modifiers;
3251         dpi->modifiers = &adpm[0];
3252         adpm[0].mod = dc;
3253         adpm[0].printed = 0;
3254         adpm[0].templates = dpi->templates;
3255
3256         i = 1;
3257         pdpm = hold_modifiers;
3258         while (pdpm != NULL
3259                && (pdpm->mod->type == DEMANGLE_COMPONENT_RESTRICT
3260                    || pdpm->mod->type == DEMANGLE_COMPONENT_VOLATILE
3261                    || pdpm->mod->type == DEMANGLE_COMPONENT_CONST))
3262           {
3263             if (! pdpm->printed)
3264               {
3265                 if (i >= sizeof adpm / sizeof adpm[0])
3266                   {
3267                     d_print_error (dpi);
3268                     return;
3269                   }
3270
3271                 adpm[i] = *pdpm;
3272                 adpm[i].next = dpi->modifiers;
3273                 dpi->modifiers = &adpm[i];
3274                 pdpm->printed = 1;
3275                 ++i;
3276               }
3277
3278             pdpm = pdpm->next;
3279           }
3280
3281         d_print_comp (dpi, d_right (dc));
3282
3283         dpi->modifiers = hold_modifiers;
3284
3285         if (adpm[0].printed)
3286           return;
3287
3288         while (i > 1)
3289           {
3290             --i;
3291             d_print_mod (dpi, adpm[i].mod);
3292           }
3293
3294         d_print_array_type (dpi, dc, dpi->modifiers);
3295
3296         return;
3297       }
3298
3299     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
3300       {
3301         struct d_print_mod dpm;
3302
3303         dpm.next = dpi->modifiers;
3304         dpi->modifiers = &dpm;
3305         dpm.mod = dc;
3306         dpm.printed = 0;
3307         dpm.templates = dpi->templates;
3308
3309         d_print_comp (dpi, d_right (dc));
3310
3311         /* If the modifier didn't get printed by the type, print it
3312            now.  */
3313         if (! dpm.printed)
3314           {
3315             d_append_char (dpi, ' ');
3316             d_print_comp (dpi, d_left (dc));
3317             d_append_string (dpi, "::*");
3318           }
3319
3320         dpi->modifiers = dpm.next;
3321
3322         return;
3323       }
3324
3325     case DEMANGLE_COMPONENT_ARGLIST:
3326     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
3327       d_print_comp (dpi, d_left (dc));
3328       if (d_right (dc) != NULL)
3329         {
3330           d_append_string (dpi, ", ");
3331           d_print_comp (dpi, d_right (dc));
3332         }
3333       return;
3334
3335     case DEMANGLE_COMPONENT_OPERATOR:
3336       {
3337         char c;
3338
3339         d_append_string (dpi, "operator");
3340         c = dc->u.s_operator.op->name[0];
3341         if (IS_LOWER (c))
3342           d_append_char (dpi, ' ');
3343         d_append_buffer (dpi, dc->u.s_operator.op->name,
3344                          dc->u.s_operator.op->len);
3345         return;
3346       }
3347
3348     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
3349       d_append_string (dpi, "operator ");
3350       d_print_comp (dpi, dc->u.s_extended_operator.name);
3351       return;
3352
3353     case DEMANGLE_COMPONENT_CAST:
3354       d_append_string (dpi, "operator ");
3355       d_print_cast (dpi, dc);
3356       return;
3357
3358     case DEMANGLE_COMPONENT_UNARY:
3359       if (d_left (dc)->type != DEMANGLE_COMPONENT_CAST)
3360         d_print_expr_op (dpi, d_left (dc));
3361       else
3362         {
3363           d_append_char (dpi, '(');
3364           d_print_cast (dpi, d_left (dc));
3365           d_append_char (dpi, ')');
3366         }
3367       d_append_char (dpi, '(');
3368       d_print_comp (dpi, d_right (dc));
3369       d_append_char (dpi, ')');
3370       return;
3371
3372     case DEMANGLE_COMPONENT_BINARY:
3373       if (d_right (dc)->type != DEMANGLE_COMPONENT_BINARY_ARGS)
3374         {
3375           d_print_error (dpi);
3376           return;
3377         }
3378
3379       /* We wrap an expression which uses the greater-than operator in
3380          an extra layer of parens so that it does not get confused
3381          with the '>' which ends the template parameters.  */
3382       if (d_left (dc)->type == DEMANGLE_COMPONENT_OPERATOR
3383           && d_left (dc)->u.s_operator.op->len == 1
3384           && d_left (dc)->u.s_operator.op->name[0] == '>')
3385         d_append_char (dpi, '(');
3386
3387       d_append_char (dpi, '(');
3388       d_print_comp (dpi, d_left (d_right (dc)));
3389       d_append_string (dpi, ") ");
3390       d_print_expr_op (dpi, d_left (dc));
3391       d_append_string (dpi, " (");
3392       d_print_comp (dpi, d_right (d_right (dc)));
3393       d_append_char (dpi, ')');
3394
3395       if (d_left (dc)->type == DEMANGLE_COMPONENT_OPERATOR
3396           && d_left (dc)->u.s_operator.op->len == 1
3397           && d_left (dc)->u.s_operator.op->name[0] == '>')
3398         d_append_char (dpi, ')');
3399
3400       return;
3401
3402     case DEMANGLE_COMPONENT_BINARY_ARGS:
3403       /* We should only see this as part of DEMANGLE_COMPONENT_BINARY.  */
3404       d_print_error (dpi);
3405       return;
3406
3407     case DEMANGLE_COMPONENT_TRINARY:
3408       if (d_right (dc)->type != DEMANGLE_COMPONENT_TRINARY_ARG1
3409           || d_right (d_right (dc))->type != DEMANGLE_COMPONENT_TRINARY_ARG2)
3410         {
3411           d_print_error (dpi);
3412           return;
3413         }
3414       d_append_char (dpi, '(');
3415       d_print_comp (dpi, d_left (d_right (dc)));
3416       d_append_string (dpi, ") ");
3417       d_print_expr_op (dpi, d_left (dc));
3418       d_append_string (dpi, " (");
3419       d_print_comp (dpi, d_left (d_right (d_right (dc))));
3420       d_append_string (dpi, ") : (");
3421       d_print_comp (dpi, d_right (d_right (d_right (dc))));
3422       d_append_char (dpi, ')');
3423       return;
3424
3425     case DEMANGLE_COMPONENT_TRINARY_ARG1:
3426     case DEMANGLE_COMPONENT_TRINARY_ARG2:
3427       /* We should only see these are part of DEMANGLE_COMPONENT_TRINARY.  */
3428       d_print_error (dpi);
3429       return;
3430
3431     case DEMANGLE_COMPONENT_LITERAL:
3432     case DEMANGLE_COMPONENT_LITERAL_NEG:
3433       {
3434         enum d_builtin_type_print tp;
3435
3436         /* For some builtin types, produce simpler output.  */
3437         tp = D_PRINT_DEFAULT;
3438         if (d_left (dc)->type == DEMANGLE_COMPONENT_BUILTIN_TYPE)
3439           {
3440             tp = d_left (dc)->u.s_builtin.type->print;
3441             switch (tp)
3442               {
3443               case D_PRINT_INT:
3444               case D_PRINT_UNSIGNED:
3445               case D_PRINT_LONG:
3446               case D_PRINT_UNSIGNED_LONG:
3447               case D_PRINT_LONG_LONG:
3448               case D_PRINT_UNSIGNED_LONG_LONG:
3449                 if (d_right (dc)->type == DEMANGLE_COMPONENT_NAME)
3450                   {
3451                     if (dc->type == DEMANGLE_COMPONENT_LITERAL_NEG)
3452                       d_append_char (dpi, '-');
3453                     d_print_comp (dpi, d_right (dc));
3454                     switch (tp)
3455                       {
3456                       default:
3457                         break;
3458                       case D_PRINT_UNSIGNED:
3459                         d_append_char (dpi, 'u');
3460                         break;
3461                       case D_PRINT_LONG:
3462                         d_append_char (dpi, 'l');
3463                         break;
3464                       case D_PRINT_UNSIGNED_LONG:
3465                         d_append_string (dpi, "ul");
3466                         break;
3467                       case D_PRINT_LONG_LONG:
3468                         d_append_string (dpi, "ll");
3469                         break;
3470                       case D_PRINT_UNSIGNED_LONG_LONG:
3471                         d_append_string (dpi, "ull");
3472                         break;
3473                       }
3474                     return;
3475                   }
3476                 break;
3477
3478               case D_PRINT_BOOL:
3479                 if (d_right (dc)->type == DEMANGLE_COMPONENT_NAME
3480                     && d_right (dc)->u.s_name.len == 1
3481                     && dc->type == DEMANGLE_COMPONENT_LITERAL)
3482                   {
3483                     switch (d_right (dc)->u.s_name.s[0])
3484                       {
3485                       case '0':
3486                         d_append_string (dpi, "false");
3487                         return;
3488                       case '1':
3489                         d_append_string (dpi, "true");
3490                         return;
3491                       default:
3492                         break;
3493                       }
3494                   }
3495                 break;
3496
3497               default:
3498                 break;
3499               }
3500           }
3501
3502         d_append_char (dpi, '(');
3503         d_print_comp (dpi, d_left (dc));
3504         d_append_char (dpi, ')');
3505         if (dc->type == DEMANGLE_COMPONENT_LITERAL_NEG)
3506           d_append_char (dpi, '-');
3507         if (tp == D_PRINT_FLOAT)
3508           d_append_char (dpi, '[');
3509         d_print_comp (dpi, d_right (dc));
3510         if (tp == D_PRINT_FLOAT)
3511           d_append_char (dpi, ']');
3512       }
3513       return;
3514
3515     default:
3516       d_print_error (dpi);
3517       return;
3518     }
3519 }
3520
3521 /* Print a Java dentifier.  For Java we try to handle encoded extended
3522    Unicode characters.  The C++ ABI doesn't mention Unicode encoding,
3523    so we don't it for C++.  Characters are encoded as
3524    __U<hex-char>+_.  */
3525
3526 static void
3527 d_print_java_identifier (struct d_print_info *dpi, const char *name, int len)
3528 {
3529   const char *p;
3530   const char *end;
3531
3532   end = name + len;
3533   for (p = name; p < end; ++p)
3534     {
3535       if (end - p > 3
3536           && p[0] == '_'
3537           && p[1] == '_'
3538           && p[2] == 'U')
3539         {
3540           unsigned long c;
3541           const char *q;
3542
3543           c = 0;
3544           for (q = p + 3; q < end; ++q)
3545             {
3546               int dig;
3547
3548               if (IS_DIGIT (*q))
3549                 dig = *q - '0';
3550               else if (*q >= 'A' && *q <= 'F')
3551                 dig = *q - 'A' + 10;
3552               else if (*q >= 'a' && *q <= 'f')
3553                 dig = *q - 'a' + 10;
3554               else
3555                 break;
3556
3557               c = c * 16 + dig;
3558             }
3559           /* If the Unicode character is larger than 256, we don't try
3560              to deal with it here.  FIXME.  */
3561           if (q < end && *q == '_' && c < 256)
3562             {
3563               d_append_char (dpi, c);
3564               p = q;
3565               continue;
3566             }
3567         }
3568
3569       d_append_char (dpi, *p);
3570     }
3571 }
3572
3573 /* Print a list of modifiers.  SUFFIX is 1 if we are printing
3574    qualifiers on this after printing a function.  */
3575
3576 static void
3577 d_print_mod_list (struct d_print_info *dpi,
3578                   struct d_print_mod *mods, int suffix)
3579 {
3580   struct d_print_template *hold_dpt;
3581
3582   if (mods == NULL || d_print_saw_error (dpi))
3583     return;
3584
3585   if (mods->printed
3586       || (! suffix
3587           && (mods->mod->type == DEMANGLE_COMPONENT_RESTRICT_THIS
3588               || mods->mod->type == DEMANGLE_COMPONENT_VOLATILE_THIS
3589               || mods->mod->type == DEMANGLE_COMPONENT_CONST_THIS)))
3590     {
3591       d_print_mod_list (dpi, mods->next, suffix);
3592       return;
3593     }
3594
3595   mods->printed = 1;
3596
3597   hold_dpt = dpi->templates;
3598   dpi->templates = mods->templates;
3599
3600   if (mods->mod->type == DEMANGLE_COMPONENT_FUNCTION_TYPE)
3601     {
3602       d_print_function_type (dpi, mods->mod, mods->next);
3603       dpi->templates = hold_dpt;
3604       return;
3605     }
3606   else if (mods->mod->type == DEMANGLE_COMPONENT_ARRAY_TYPE)
3607     {
3608       d_print_array_type (dpi, mods->mod, mods->next);
3609       dpi->templates = hold_dpt;
3610       return;
3611     }
3612   else if (mods->mod->type == DEMANGLE_COMPONENT_LOCAL_NAME)
3613     {
3614       struct d_print_mod *hold_modifiers;
3615       struct demangle_component *dc;
3616
3617       /* When this is on the modifier stack, we have pulled any
3618          qualifiers off the right argument already.  Otherwise, we
3619          print it as usual, but don't let the left argument see any
3620          modifiers.  */
3621
3622       hold_modifiers = dpi->modifiers;
3623       dpi->modifiers = NULL;
3624       d_print_comp (dpi, d_left (mods->mod));
3625       dpi->modifiers = hold_modifiers;
3626
3627       if ((dpi->options & DMGL_JAVA) == 0)
3628         d_append_string (dpi, "::");
3629       else
3630         d_append_char (dpi, '.');
3631
3632       dc = d_right (mods->mod);
3633       while (dc->type == DEMANGLE_COMPONENT_RESTRICT_THIS
3634              || dc->type == DEMANGLE_COMPONENT_VOLATILE_THIS
3635              || dc->type == DEMANGLE_COMPONENT_CONST_THIS)
3636         dc = d_left (dc);
3637
3638       d_print_comp (dpi, dc);
3639
3640       dpi->templates = hold_dpt;
3641       return;
3642     }
3643
3644   d_print_mod (dpi, mods->mod);
3645
3646   dpi->templates = hold_dpt;
3647
3648   d_print_mod_list (dpi, mods->next, suffix);
3649 }
3650
3651 /* Print a modifier.  */
3652
3653 static void
3654 d_print_mod (struct d_print_info *dpi,
3655              const struct demangle_component *mod)
3656 {
3657   switch (mod->type)
3658     {
3659     case DEMANGLE_COMPONENT_RESTRICT:
3660     case DEMANGLE_COMPONENT_RESTRICT_THIS:
3661       d_append_string (dpi, " restrict");
3662       return;
3663     case DEMANGLE_COMPONENT_VOLATILE:
3664     case DEMANGLE_COMPONENT_VOLATILE_THIS:
3665       d_append_string (dpi, " volatile");
3666       return;
3667     case DEMANGLE_COMPONENT_CONST:
3668     case DEMANGLE_COMPONENT_CONST_THIS:
3669       d_append_string (dpi, " const");
3670       return;
3671     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
3672       d_append_char (dpi, ' ');
3673       d_print_comp (dpi, d_right (mod));
3674       return;
3675     case DEMANGLE_COMPONENT_POINTER:
3676       /* There is no pointer symbol in Java.  */
3677       if ((dpi->options & DMGL_JAVA) == 0)
3678         d_append_char (dpi, '*');
3679       return;
3680     case DEMANGLE_COMPONENT_REFERENCE:
3681       d_append_char (dpi, '&');
3682       return;
3683     case DEMANGLE_COMPONENT_COMPLEX:
3684       d_append_string (dpi, "complex ");
3685       return;
3686     case DEMANGLE_COMPONENT_IMAGINARY:
3687       d_append_string (dpi, "imaginary ");
3688       return;
3689     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
3690       if (d_last_char (dpi) != '(')
3691         d_append_char (dpi, ' ');
3692       d_print_comp (dpi, d_left (mod));
3693       d_append_string (dpi, "::*");
3694       return;
3695     case DEMANGLE_COMPONENT_TYPED_NAME:
3696       d_print_comp (dpi, d_left (mod));
3697       return;
3698     default:
3699       /* Otherwise, we have something that won't go back on the
3700          modifier stack, so we can just print it.  */
3701       d_print_comp (dpi, mod);
3702       return;
3703     }
3704 }
3705
3706 /* Print a function type, except for the return type.  */
3707
3708 static void
3709 d_print_function_type (struct d_print_info *dpi,
3710                        const struct demangle_component *dc,
3711                        struct d_print_mod *mods)
3712 {
3713   int need_paren;
3714   int saw_mod;
3715   int need_space;
3716   struct d_print_mod *p;
3717   struct d_print_mod *hold_modifiers;
3718
3719   need_paren = 0;
3720   saw_mod = 0;
3721   need_space = 0;
3722   for (p = mods; p != NULL; p = p->next)
3723     {
3724       if (p->printed)
3725         break;
3726
3727       saw_mod = 1;
3728       switch (p->mod->type)
3729         {
3730         case DEMANGLE_COMPONENT_POINTER:
3731         case DEMANGLE_COMPONENT_REFERENCE:
3732           need_paren = 1;
3733           break;
3734         case DEMANGLE_COMPONENT_RESTRICT:
3735         case DEMANGLE_COMPONENT_VOLATILE:
3736         case DEMANGLE_COMPONENT_CONST:
3737         case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
3738         case DEMANGLE_COMPONENT_COMPLEX:
3739         case DEMANGLE_COMPONENT_IMAGINARY:
3740         case DEMANGLE_COMPONENT_PTRMEM_TYPE:
3741           need_space = 1;
3742           need_paren = 1;
3743           break;
3744         case DEMANGLE_COMPONENT_RESTRICT_THIS:
3745         case DEMANGLE_COMPONENT_VOLATILE_THIS:
3746         case DEMANGLE_COMPONENT_CONST_THIS:
3747           break;
3748         default:
3749           break;
3750         }
3751       if (need_paren)
3752         break;
3753     }
3754
3755   if (d_left (dc) != NULL && ! saw_mod)
3756     need_paren = 1;
3757
3758   if (need_paren)
3759     {
3760       if (! need_space)
3761         {
3762           if (d_last_char (dpi) != '('
3763               && d_last_char (dpi) != '*')
3764             need_space = 1;
3765         }
3766       if (need_space && d_last_char (dpi) != ' ')
3767         d_append_char (dpi, ' ');
3768       d_append_char (dpi, '(');
3769     }
3770
3771   hold_modifiers = dpi->modifiers;
3772   dpi->modifiers = NULL;
3773
3774   d_print_mod_list (dpi, mods, 0);
3775
3776   if (need_paren)
3777     d_append_char (dpi, ')');
3778
3779   d_append_char (dpi, '(');
3780
3781   if (d_right (dc) != NULL)
3782     d_print_comp (dpi, d_right (dc));
3783
3784   d_append_char (dpi, ')');
3785
3786   d_print_mod_list (dpi, mods, 1);
3787
3788   dpi->modifiers = hold_modifiers;
3789 }
3790
3791 /* Print an array type, except for the element type.  */
3792
3793 static void
3794 d_print_array_type (struct d_print_info *dpi,
3795                     const struct demangle_component *dc,
3796                     struct d_print_mod *mods)
3797 {
3798   int need_space;
3799
3800   need_space = 1;
3801   if (mods != NULL)
3802     {
3803       int need_paren;
3804       struct d_print_mod *p;
3805
3806       need_paren = 0;
3807       for (p = mods; p != NULL; p = p->next)
3808         {
3809           if (! p->printed)
3810             {
3811               if (p->mod->type == DEMANGLE_COMPONENT_ARRAY_TYPE)
3812                 {
3813                   need_space = 0;
3814                   break;
3815                 }
3816               else
3817                 {
3818                   need_paren = 1;
3819                   need_space = 1;
3820                   break;
3821                 }
3822             }
3823         }
3824
3825       if (need_paren)
3826         d_append_string (dpi, " (");
3827
3828       d_print_mod_list (dpi, mods, 0);
3829
3830       if (need_paren)
3831         d_append_char (dpi, ')');
3832     }
3833
3834   if (need_space)
3835     d_append_char (dpi, ' ');
3836
3837   d_append_char (dpi, '[');
3838
3839   if (d_left (dc) != NULL)
3840     d_print_comp (dpi, d_left (dc));
3841
3842   d_append_char (dpi, ']');
3843 }
3844
3845 /* Print an operator in an expression.  */
3846
3847 static void
3848 d_print_expr_op (struct d_print_info *dpi,
3849                  const struct demangle_component *dc)
3850 {
3851   if (dc->type == DEMANGLE_COMPONENT_OPERATOR)
3852     d_append_buffer (dpi, dc->u.s_operator.op->name,
3853                      dc->u.s_operator.op->len);
3854   else
3855     d_print_comp (dpi, dc);
3856 }
3857
3858 /* Print a cast.  */
3859
3860 static void
3861 d_print_cast (struct d_print_info *dpi,
3862               const struct demangle_component *dc)
3863 {
3864   if (d_left (dc)->type != DEMANGLE_COMPONENT_TEMPLATE)
3865     d_print_comp (dpi, d_left (dc));
3866   else
3867     {
3868       struct d_print_mod *hold_dpm;
3869       struct d_print_template dpt;
3870
3871       /* It appears that for a templated cast operator, we need to put
3872          the template parameters in scope for the operator name, but
3873          not for the parameters.  The effect is that we need to handle
3874          the template printing here.  */
3875
3876       hold_dpm = dpi->modifiers;
3877       dpi->modifiers = NULL;
3878
3879       dpt.next = dpi->templates;
3880       dpi->templates = &dpt;
3881       dpt.template_decl = d_left (dc);
3882
3883       d_print_comp (dpi, d_left (d_left (dc)));
3884
3885       dpi->templates = dpt.next;
3886
3887       if (d_last_char (dpi) == '<')
3888         d_append_char (dpi, ' ');
3889       d_append_char (dpi, '<');
3890       d_print_comp (dpi, d_right (d_left (dc)));
3891       /* Avoid generating two consecutive '>' characters, to avoid
3892          the C++ syntactic ambiguity.  */
3893       if (d_last_char (dpi) == '>')
3894         d_append_char (dpi, ' ');
3895       d_append_char (dpi, '>');
3896
3897       dpi->modifiers = hold_dpm;
3898     }
3899 }
3900
3901 /* Initialize the information structure we use to pass around
3902    information.  */
3903
3904 CP_STATIC_IF_GLIBCPP_V3
3905 void
3906 cplus_demangle_init_info (const char *mangled, int options, size_t len,
3907                           struct d_info *di)
3908 {
3909   di->s = mangled;
3910   di->send = mangled + len;
3911   di->options = options;
3912
3913   di->n = mangled;
3914
3915   /* We can not need more components than twice the number of chars in
3916      the mangled string.  Most components correspond directly to
3917      chars, but the ARGLIST types are exceptions.  */
3918   di->num_comps = 2 * len;
3919   di->next_comp = 0;
3920
3921   /* Similarly, we can not need more substitutions than there are
3922      chars in the mangled string.  */
3923   di->num_subs = len;
3924   di->next_sub = 0;
3925   di->did_subs = 0;
3926
3927   di->last_name = NULL;
3928
3929   di->expansion = 0;
3930 }
3931
3932 /* Internal implementation for the demangler.  If MANGLED is a g++ v3 ABI
3933    mangled name, return strings in repeated callback giving the demangled
3934    name.  OPTIONS is the usual libiberty demangler options.  On success,
3935    this returns 1.  On failure, returns 0.  */
3936
3937 static int
3938 d_demangle_callback (const char *mangled, int options,
3939                      demangle_callbackref callback, void *opaque)
3940 {
3941   int type;
3942   struct d_info di;
3943   struct demangle_component *dc;
3944   int status;
3945
3946   if (mangled[0] == '_' && mangled[1] == 'Z')
3947     type = 0;
3948   else if (strncmp (mangled, "_GLOBAL_", 8) == 0
3949            && (mangled[8] == '.' || mangled[8] == '_' || mangled[8] == '$')
3950            && (mangled[9] == 'D' || mangled[9] == 'I')
3951            && mangled[10] == '_')
3952     {
3953       const char *intro;
3954
3955       intro = (mangled[9] == 'I')
3956               ? "global constructors keyed to "
3957               : "global destructors keyed to ";
3958
3959       callback (intro, strlen (intro), opaque);
3960       callback (mangled + 11, strlen (mangled + 11), opaque);
3961       return 1;
3962     }
3963   else
3964     {
3965       if ((options & DMGL_TYPES) == 0)
3966         return 0;
3967       type = 1;
3968     }
3969
3970   cplus_demangle_init_info (mangled, options, strlen (mangled), &di);
3971
3972   {
3973 #ifdef CP_DYNAMIC_ARRAYS
3974     __extension__ struct demangle_component comps[di.num_comps];
3975     __extension__ struct demangle_component *subs[di.num_subs];
3976
3977     di.comps = comps;
3978     di.subs = subs;
3979 #else
3980     di.comps = alloca (di.num_comps * sizeof (*di.comps));
3981     di.subs = alloca (di.num_subs * sizeof (*di.subs));
3982 #endif
3983
3984     if (type)
3985       dc = cplus_demangle_type (&di);
3986     else
3987       dc = cplus_demangle_mangled_name (&di, 1);
3988
3989     /* If DMGL_PARAMS is set, then if we didn't consume the entire
3990        mangled string, then we didn't successfully demangle it.  If
3991        DMGL_PARAMS is not set, we didn't look at the trailing
3992        parameters.  */
3993     if (((options & DMGL_PARAMS) != 0) && d_peek_char (&di) != '\0')
3994       dc = NULL;
3995
3996 #ifdef CP_DEMANGLE_DEBUG
3997     d_dump (dc, 0);
3998 #endif
3999
4000     status = (dc != NULL)
4001              ? cplus_demangle_print_callback (options, dc, callback, opaque)
4002              : 0;
4003   }
4004
4005   return status;
4006 }
4007
4008 /* Entry point for the demangler.  If MANGLED is a g++ v3 ABI mangled
4009    name, return a buffer allocated with malloc holding the demangled
4010    name.  OPTIONS is the usual libiberty demangler options.  On
4011    success, this sets *PALC to the allocated size of the returned
4012    buffer.  On failure, this sets *PALC to 0 for a bad name, or 1 for
4013    a memory allocation failure, and returns NULL.  */
4014
4015 static char *
4016 d_demangle (const char *mangled, int options, size_t *palc)
4017 {
4018   struct d_growable_string dgs;
4019   int status;
4020
4021   d_growable_string_init (&dgs, 0);
4022
4023   status = d_demangle_callback (mangled, options,
4024                                 d_growable_string_callback_adapter, &dgs);
4025   if (status == 0)
4026     {
4027       free (dgs.buf);
4028       *palc = 0;
4029       return NULL;
4030     }
4031
4032   *palc = dgs.allocation_failure ? 1 : 0;
4033   return dgs.buf;
4034 }
4035
4036 #if defined(IN_LIBGCC2) || defined(IN_GLIBCPP_V3)
4037
4038 extern char *__cxa_demangle (const char *, char *, size_t *, int *);
4039
4040 /* ia64 ABI-mandated entry point in the C++ runtime library for
4041    performing demangling.  MANGLED_NAME is a NUL-terminated character
4042    string containing the name to be demangled.
4043
4044    OUTPUT_BUFFER is a region of memory, allocated with malloc, of
4045    *LENGTH bytes, into which the demangled name is stored.  If
4046    OUTPUT_BUFFER is not long enough, it is expanded using realloc.
4047    OUTPUT_BUFFER may instead be NULL; in that case, the demangled name
4048    is placed in a region of memory allocated with malloc.
4049
4050    If LENGTH is non-NULL, the length of the buffer containing the
4051    demangled name, is placed in *LENGTH.
4052
4053    The return value is a pointer to the start of the NUL-terminated
4054    demangled name, or NULL if the demangling fails.  The caller is
4055    responsible for deallocating this memory using free.
4056
4057    *STATUS is set to one of the following values:
4058       0: The demangling operation succeeded.
4059      -1: A memory allocation failure occurred.
4060      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
4061      -3: One of the arguments is invalid.
4062
4063    The demangling is performed using the C++ ABI mangling rules, with
4064    GNU extensions.  */
4065
4066 char *
4067 __cxa_demangle (const char *mangled_name, char *output_buffer,
4068                 size_t *length, int *status)
4069 {
4070   char *demangled;
4071   size_t alc;
4072
4073   if (mangled_name == NULL)
4074     {
4075       if (status != NULL)
4076         *status = -3;
4077       return NULL;
4078     }
4079
4080   if (output_buffer != NULL && length == NULL)
4081     {
4082       if (status != NULL)
4083         *status = -3;
4084       return NULL;
4085     }
4086
4087   demangled = d_demangle (mangled_name, DMGL_PARAMS | DMGL_TYPES, &alc);
4088
4089   if (demangled == NULL)
4090     {
4091       if (status != NULL)
4092         {
4093           if (alc == 1)
4094             *status = -1;
4095           else
4096             *status = -2;
4097         }
4098       return NULL;
4099     }
4100
4101   if (output_buffer == NULL)
4102     {
4103       if (length != NULL)
4104         *length = alc;
4105     }
4106   else
4107     {
4108       if (strlen (demangled) < *length)
4109         {
4110           strcpy (output_buffer, demangled);
4111           free (demangled);
4112           demangled = output_buffer;
4113         }
4114       else
4115         {
4116           free (output_buffer);
4117           *length = alc;
4118         }
4119     }
4120
4121   if (status != NULL)
4122     *status = 0;
4123
4124   return demangled;
4125 }
4126
4127 extern int __gcclibcxx_demangle_callback (const char *,
4128                                           void (*)
4129                                             (const char *, size_t, void *),
4130                                           void *);
4131
4132 /* Alternative, allocationless entry point in the C++ runtime library
4133    for performing demangling.  MANGLED_NAME is a NUL-terminated character
4134    string containing the name to be demangled.
4135
4136    CALLBACK is a callback function, called with demangled string
4137    segments as demangling progresses; it is called at least once,
4138    but may be called more than once.  OPAQUE is a generalized pointer
4139    used as a callback argument.
4140
4141    The return code is one of the following values, equivalent to
4142    the STATUS values of __cxa_demangle() (excluding -1, since this
4143    function performs no memory allocations):
4144       0: The demangling operation succeeded.
4145      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
4146      -3: One of the arguments is invalid.
4147
4148    The demangling is performed using the C++ ABI mangling rules, with
4149    GNU extensions.  */
4150
4151 int
4152 __gcclibcxx_demangle_callback (const char *mangled_name,
4153                                void (*callback) (const char *, size_t, void *),
4154                                void *opaque)
4155 {
4156   int status;
4157
4158   if (mangled_name == NULL || callback == NULL)
4159     return -3;
4160
4161   status = d_demangle_callback (mangled_name, DMGL_PARAMS | DMGL_TYPES,
4162                                 callback, opaque);
4163   if (status == 0)
4164     return -2;
4165
4166   return 0;
4167 }
4168
4169 #else /* ! (IN_LIBGCC2 || IN_GLIBCPP_V3) */
4170
4171 /* Entry point for libiberty demangler.  If MANGLED is a g++ v3 ABI
4172    mangled name, return a buffer allocated with malloc holding the
4173    demangled name.  Otherwise, return NULL.  */
4174
4175 char *
4176 cplus_demangle_v3 (const char *mangled, int options)
4177 {
4178   size_t alc;
4179
4180   return d_demangle (mangled, options, &alc);
4181 }
4182
4183 int
4184 cplus_demangle_v3_callback (const char *mangled, int options,
4185                             demangle_callbackref callback, void *opaque)
4186 {
4187   return d_demangle_callback (mangled, options, callback, opaque);
4188 }
4189
4190 /* Demangle a Java symbol.  Java uses a subset of the V3 ABI C++ mangling 
4191    conventions, but the output formatting is a little different.
4192    This instructs the C++ demangler not to emit pointer characters ("*"), to
4193    use Java's namespace separator symbol ("." instead of "::"), and to output
4194    JArray<TYPE> as TYPE[].  */
4195
4196 char *
4197 java_demangle_v3 (const char *mangled)
4198 {
4199   size_t alc;
4200
4201   return d_demangle (mangled, DMGL_JAVA | DMGL_PARAMS | DMGL_RET_POSTFIX, &alc);
4202 }
4203
4204 int
4205 java_demangle_v3_callback (const char *mangled,
4206                            demangle_callbackref callback, void *opaque)
4207 {
4208   return d_demangle_callback (mangled,
4209                               DMGL_JAVA | DMGL_PARAMS | DMGL_RET_POSTFIX,
4210                               callback, opaque);
4211 }
4212
4213 #endif /* IN_LIBGCC2 || IN_GLIBCPP_V3 */
4214
4215 #ifndef IN_GLIBCPP_V3
4216
4217 /* Demangle a string in order to find out whether it is a constructor
4218    or destructor.  Return non-zero on success.  Set *CTOR_KIND and
4219    *DTOR_KIND appropriately.  */
4220
4221 static int
4222 is_ctor_or_dtor (const char *mangled,
4223                  enum gnu_v3_ctor_kinds *ctor_kind,
4224                  enum gnu_v3_dtor_kinds *dtor_kind)
4225 {
4226   struct d_info di;
4227   struct demangle_component *dc;
4228   int ret;
4229
4230   *ctor_kind = (enum gnu_v3_ctor_kinds) 0;
4231   *dtor_kind = (enum gnu_v3_dtor_kinds) 0;
4232
4233   cplus_demangle_init_info (mangled, DMGL_GNU_V3, strlen (mangled), &di);
4234
4235   {
4236 #ifdef CP_DYNAMIC_ARRAYS
4237     __extension__ struct demangle_component comps[di.num_comps];
4238     __extension__ struct demangle_component *subs[di.num_subs];
4239
4240     di.comps = comps;
4241     di.subs = subs;
4242 #else
4243     di.comps = alloca (di.num_comps * sizeof (*di.comps));
4244     di.subs = alloca (di.num_subs * sizeof (*di.subs));
4245 #endif
4246
4247     dc = cplus_demangle_mangled_name (&di, 1);
4248
4249     /* Note that because we did not pass DMGL_PARAMS, we don't expect
4250        to demangle the entire string.  */
4251
4252     ret = 0;
4253     while (dc != NULL)
4254       {
4255         switch (dc->type)
4256           {
4257           default:
4258             dc = NULL;
4259             break;
4260           case DEMANGLE_COMPONENT_TYPED_NAME:
4261           case DEMANGLE_COMPONENT_TEMPLATE:
4262           case DEMANGLE_COMPONENT_RESTRICT_THIS:
4263           case DEMANGLE_COMPONENT_VOLATILE_THIS:
4264           case DEMANGLE_COMPONENT_CONST_THIS:
4265             dc = d_left (dc);
4266             break;
4267           case DEMANGLE_COMPONENT_QUAL_NAME:
4268           case DEMANGLE_COMPONENT_LOCAL_NAME:
4269             dc = d_right (dc);
4270             break;
4271           case DEMANGLE_COMPONENT_CTOR:
4272             *ctor_kind = dc->u.s_ctor.kind;
4273             ret = 1;
4274             dc = NULL;
4275             break;
4276           case DEMANGLE_COMPONENT_DTOR:
4277             *dtor_kind = dc->u.s_dtor.kind;
4278             ret = 1;
4279             dc = NULL;
4280             break;
4281           }
4282       }
4283   }
4284
4285   return ret;
4286 }
4287
4288 /* Return whether NAME is the mangled form of a g++ V3 ABI constructor
4289    name.  A non-zero return indicates the type of constructor.  */
4290
4291 enum gnu_v3_ctor_kinds
4292 is_gnu_v3_mangled_ctor (const char *name)
4293 {
4294   enum gnu_v3_ctor_kinds ctor_kind;
4295   enum gnu_v3_dtor_kinds dtor_kind;
4296
4297   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
4298     return (enum gnu_v3_ctor_kinds) 0;
4299   return ctor_kind;
4300 }
4301
4302
4303 /* Return whether NAME is the mangled form of a g++ V3 ABI destructor
4304    name.  A non-zero return indicates the type of destructor.  */
4305
4306 enum gnu_v3_dtor_kinds
4307 is_gnu_v3_mangled_dtor (const char *name)
4308 {
4309   enum gnu_v3_ctor_kinds ctor_kind;
4310   enum gnu_v3_dtor_kinds dtor_kind;
4311
4312   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
4313     return (enum gnu_v3_dtor_kinds) 0;
4314   return dtor_kind;
4315 }
4316
4317 #endif /* IN_GLIBCPP_V3 */
4318
4319 #ifdef STANDALONE_DEMANGLER
4320
4321 #include "getopt.h"
4322 #include "dyn-string.h"
4323
4324 static void print_usage (FILE* fp, int exit_value);
4325
4326 #define IS_ALPHA(CHAR)                                                  \
4327   (((CHAR) >= 'a' && (CHAR) <= 'z')                                     \
4328    || ((CHAR) >= 'A' && (CHAR) <= 'Z'))
4329
4330 /* Non-zero if CHAR is a character than can occur in a mangled name.  */
4331 #define is_mangled_char(CHAR)                                           \
4332   (IS_ALPHA (CHAR) || IS_DIGIT (CHAR)                                   \
4333    || (CHAR) == '_' || (CHAR) == '.' || (CHAR) == '$')
4334
4335 /* The name of this program, as invoked.  */
4336 const char* program_name;
4337
4338 /* Prints usage summary to FP and then exits with EXIT_VALUE.  */
4339
4340 static void
4341 print_usage (FILE* fp, int exit_value)
4342 {
4343   fprintf (fp, "Usage: %s [options] [names ...]\n", program_name);
4344   fprintf (fp, "Options:\n");
4345   fprintf (fp, "  -h,--help       Display this message.\n");
4346   fprintf (fp, "  -p,--no-params  Don't display function parameters\n");
4347   fprintf (fp, "  -v,--verbose    Produce verbose demanglings.\n");
4348   fprintf (fp, "If names are provided, they are demangled.  Otherwise filters standard input.\n");
4349
4350   exit (exit_value);
4351 }
4352
4353 /* Option specification for getopt_long.  */
4354 static const struct option long_options[] = 
4355 {
4356   { "help",      no_argument, NULL, 'h' },
4357   { "no-params", no_argument, NULL, 'p' },
4358   { "verbose",   no_argument, NULL, 'v' },
4359   { NULL,        no_argument, NULL, 0   },
4360 };
4361
4362 /* Main entry for a demangling filter executable.  It will demangle
4363    its command line arguments, if any.  If none are provided, it will
4364    filter stdin to stdout, replacing any recognized mangled C++ names
4365    with their demangled equivalents.  */
4366
4367 int
4368 main (int argc, char *argv[])
4369 {
4370   int i;
4371   int opt_char;
4372   int options = DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES;
4373
4374   /* Use the program name of this program, as invoked.  */
4375   program_name = argv[0];
4376
4377   /* Parse options.  */
4378   do 
4379     {
4380       opt_char = getopt_long (argc, argv, "hpv", long_options, NULL);
4381       switch (opt_char)
4382         {
4383         case '?':  /* Unrecognized option.  */
4384           print_usage (stderr, 1);
4385           break;
4386
4387         case 'h':
4388           print_usage (stdout, 0);
4389           break;
4390
4391         case 'p':
4392           options &= ~ DMGL_PARAMS;
4393           break;
4394
4395         case 'v':
4396           options |= DMGL_VERBOSE;
4397           break;
4398         }
4399     }
4400   while (opt_char != -1);
4401
4402   if (optind == argc) 
4403     /* No command line arguments were provided.  Filter stdin.  */
4404     {
4405       dyn_string_t mangled = dyn_string_new (3);
4406       char *s;
4407
4408       /* Read all of input.  */
4409       while (!feof (stdin))
4410         {
4411           char c;
4412
4413           /* Pile characters into mangled until we hit one that can't
4414              occur in a mangled name.  */
4415           c = getchar ();
4416           while (!feof (stdin) && is_mangled_char (c))
4417             {
4418               dyn_string_append_char (mangled, c);
4419               if (feof (stdin))
4420                 break;
4421               c = getchar ();
4422             }
4423
4424           if (dyn_string_length (mangled) > 0)
4425             {
4426 #ifdef IN_GLIBCPP_V3
4427               s = __cxa_demangle (dyn_string_buf (mangled), NULL, NULL, NULL);
4428 #else
4429               s = cplus_demangle_v3 (dyn_string_buf (mangled), options);
4430 #endif
4431
4432               if (s != NULL)
4433                 {
4434                   fputs (s, stdout);
4435                   free (s);
4436                 }
4437               else
4438                 {
4439                   /* It might not have been a mangled name.  Print the
4440                      original text.  */
4441                   fputs (dyn_string_buf (mangled), stdout);
4442                 }
4443
4444               dyn_string_clear (mangled);
4445             }
4446
4447           /* If we haven't hit EOF yet, we've read one character that
4448              can't occur in a mangled name, so print it out.  */
4449           if (!feof (stdin))
4450             putchar (c);
4451         }
4452
4453       dyn_string_delete (mangled);
4454     }
4455   else
4456     /* Demangle command line arguments.  */
4457     {
4458       /* Loop over command line arguments.  */
4459       for (i = optind; i < argc; ++i)
4460         {
4461           char *s;
4462 #ifdef IN_GLIBCPP_V3
4463           int status;
4464 #endif
4465
4466           /* Attempt to demangle.  */
4467 #ifdef IN_GLIBCPP_V3
4468           s = __cxa_demangle (argv[i], NULL, NULL, &status);
4469 #else
4470           s = cplus_demangle_v3 (argv[i], options);
4471 #endif
4472
4473           /* If it worked, print the demangled name.  */
4474           if (s != NULL)
4475             {
4476               printf ("%s\n", s);
4477               free (s);
4478             }
4479           else
4480             {
4481 #ifdef IN_GLIBCPP_V3
4482               fprintf (stderr, "Failed: %s (status %d)\n", argv[i], status);
4483 #else
4484               fprintf (stderr, "Failed: %s\n", argv[i]);
4485 #endif
4486             }
4487         }
4488     }
4489
4490   return 0;
4491 }
4492
4493 #endif /* STANDALONE_DEMANGLER */