libiberty: sync with gcc
[platform/upstream/binutils.git] / libiberty / cp-demangle.c
1 /* Demangler for g++ V3 ABI.
2    Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
3    Free Software Foundation, Inc.
4    Written by Ian Lance Taylor <ian@wasabisystems.com>.
5
6    This file is part of the libiberty library, which is part of GCC.
7
8    This file is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    In addition to the permissions in the GNU General Public License, the
14    Free Software Foundation gives you unlimited permission to link the
15    compiled version of this file into combinations with other programs,
16    and to distribute those combinations without any restriction coming
17    from the use of this file.  (The General Public License restrictions
18    do apply in other respects; for example, they cover modification of
19    the file, and distribution when not linked into a combined
20    executable.)
21
22    This program is distributed in the hope that it will be useful,
23    but WITHOUT ANY WARRANTY; without even the implied warranty of
24    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25    GNU General Public License for more details.
26
27    You should have received a copy of the GNU General Public License
28    along with this program; if not, write to the Free Software
29    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. 
30 */
31
32 /* This code implements a demangler for the g++ V3 ABI.  The ABI is
33    described on this web page:
34        http://www.codesourcery.com/cxx-abi/abi.html#mangling
35
36    This code was written while looking at the demangler written by
37    Alex Samuel <samuel@codesourcery.com>.
38
39    This code first pulls the mangled name apart into a list of
40    components, and then walks the list generating the demangled
41    name.
42
43    This file will normally define the following functions, q.v.:
44       char *cplus_demangle_v3(const char *mangled, int options)
45       char *java_demangle_v3(const char *mangled)
46       int cplus_demangle_v3_callback(const char *mangled, int options,
47                                      demangle_callbackref callback)
48       int java_demangle_v3_callback(const char *mangled,
49                                     demangle_callbackref callback)
50       enum gnu_v3_ctor_kinds is_gnu_v3_mangled_ctor (const char *name)
51       enum gnu_v3_dtor_kinds is_gnu_v3_mangled_dtor (const char *name)
52
53    Also, the interface to the component list is public, and defined in
54    demangle.h.  The interface consists of these types, which are
55    defined in demangle.h:
56       enum demangle_component_type
57       struct demangle_component
58       demangle_callbackref
59    and these functions defined in this file:
60       cplus_demangle_fill_name
61       cplus_demangle_fill_extended_operator
62       cplus_demangle_fill_ctor
63       cplus_demangle_fill_dtor
64       cplus_demangle_print
65       cplus_demangle_print_callback
66    and other functions defined in the file cp-demint.c.
67
68    This file also defines some other functions and variables which are
69    only to be used by the file cp-demint.c.
70
71    Preprocessor macros you can define while compiling this file:
72
73    IN_LIBGCC2
74       If defined, this file defines the following functions, q.v.:
75          char *__cxa_demangle (const char *mangled, char *buf, size_t *len,
76                                int *status)
77          int __gcclibcxx_demangle_callback (const char *,
78                                             void (*)
79                                               (const char *, size_t, void *),
80                                             void *)
81       instead of cplus_demangle_v3[_callback]() and
82       java_demangle_v3[_callback]().
83
84    IN_GLIBCPP_V3
85       If defined, this file defines only __cxa_demangle() and
86       __gcclibcxx_demangle_callback(), and no other publically visible
87       functions or variables.
88
89    STANDALONE_DEMANGLER
90       If defined, this file defines a main() function which demangles
91       any arguments, or, if none, demangles stdin.
92
93    CP_DEMANGLE_DEBUG
94       If defined, turns on debugging mode, which prints information on
95       stdout about the mangled string.  This is not generally useful.
96 */
97
98 #if defined (_AIX) && !defined (__GNUC__)
99  #pragma alloca
100 #endif
101
102 #ifdef HAVE_CONFIG_H
103 #include "config.h"
104 #endif
105
106 #include <stdio.h>
107
108 #ifdef HAVE_STDLIB_H
109 #include <stdlib.h>
110 #endif
111 #ifdef HAVE_STRING_H
112 #include <string.h>
113 #endif
114
115 #ifdef HAVE_ALLOCA_H
116 # include <alloca.h>
117 #else
118 # ifndef alloca
119 #  ifdef __GNUC__
120 #   define alloca __builtin_alloca
121 #  else
122 extern char *alloca ();
123 #  endif /* __GNUC__ */
124 # endif /* alloca */
125 #endif /* HAVE_ALLOCA_H */
126
127 #include "ansidecl.h"
128 #include "libiberty.h"
129 #include "demangle.h"
130 #include "cp-demangle.h"
131
132 /* If IN_GLIBCPP_V3 is defined, some functions are made static.  We
133    also rename them via #define to avoid compiler errors when the
134    static definition conflicts with the extern declaration in a header
135    file.  */
136 #ifdef IN_GLIBCPP_V3
137
138 #define CP_STATIC_IF_GLIBCPP_V3 static
139
140 #define cplus_demangle_fill_name d_fill_name
141 static int d_fill_name (struct demangle_component *, const char *, int);
142
143 #define cplus_demangle_fill_extended_operator d_fill_extended_operator
144 static int
145 d_fill_extended_operator (struct demangle_component *, int,
146                           struct demangle_component *);
147
148 #define cplus_demangle_fill_ctor d_fill_ctor
149 static int
150 d_fill_ctor (struct demangle_component *, enum gnu_v3_ctor_kinds,
151              struct demangle_component *);
152
153 #define cplus_demangle_fill_dtor d_fill_dtor
154 static int
155 d_fill_dtor (struct demangle_component *, enum gnu_v3_dtor_kinds,
156              struct demangle_component *);
157
158 #define cplus_demangle_mangled_name d_mangled_name
159 static struct demangle_component *d_mangled_name (struct d_info *, int);
160
161 #define cplus_demangle_type d_type
162 static struct demangle_component *d_type (struct d_info *);
163
164 #define cplus_demangle_print d_print
165 static char *d_print (int, const struct demangle_component *, int, size_t *);
166
167 #define cplus_demangle_print_callback d_print_callback
168 static int d_print_callback (int, const struct demangle_component *,
169                              demangle_callbackref, void *);
170
171 #define cplus_demangle_init_info d_init_info
172 static void d_init_info (const char *, int, size_t, struct d_info *);
173
174 #else /* ! defined(IN_GLIBCPP_V3) */
175 #define CP_STATIC_IF_GLIBCPP_V3
176 #endif /* ! defined(IN_GLIBCPP_V3) */
177
178 /* See if the compiler supports dynamic arrays.  */
179
180 #ifdef __GNUC__
181 #define CP_DYNAMIC_ARRAYS
182 #else
183 #ifdef __STDC__
184 #ifdef __STDC_VERSION__
185 #if __STDC_VERSION__ >= 199901L
186 #define CP_DYNAMIC_ARRAYS
187 #endif /* __STDC__VERSION >= 199901L */
188 #endif /* defined (__STDC_VERSION__) */
189 #endif /* defined (__STDC__) */
190 #endif /* ! defined (__GNUC__) */
191
192 /* We avoid pulling in the ctype tables, to prevent pulling in
193    additional unresolved symbols when this code is used in a library.
194    FIXME: Is this really a valid reason?  This comes from the original
195    V3 demangler code.
196
197    As of this writing this file has the following undefined references
198    when compiled with -DIN_GLIBCPP_V3: realloc, free, memcpy, strcpy,
199    strcat, strlen.  */
200
201 #define IS_DIGIT(c) ((c) >= '0' && (c) <= '9')
202 #define IS_UPPER(c) ((c) >= 'A' && (c) <= 'Z')
203 #define IS_LOWER(c) ((c) >= 'a' && (c) <= 'z')
204
205 /* The prefix prepended by GCC to an identifier represnting the
206    anonymous namespace.  */
207 #define ANONYMOUS_NAMESPACE_PREFIX "_GLOBAL_"
208 #define ANONYMOUS_NAMESPACE_PREFIX_LEN \
209   (sizeof (ANONYMOUS_NAMESPACE_PREFIX) - 1)
210
211 /* Information we keep for the standard substitutions.  */
212
213 struct d_standard_sub_info
214 {
215   /* The code for this substitution.  */
216   char code;
217   /* The simple string it expands to.  */
218   const char *simple_expansion;
219   /* The length of the simple expansion.  */
220   int simple_len;
221   /* The results of a full, verbose, expansion.  This is used when
222      qualifying a constructor/destructor, or when in verbose mode.  */
223   const char *full_expansion;
224   /* The length of the full expansion.  */
225   int full_len;
226   /* What to set the last_name field of d_info to; NULL if we should
227      not set it.  This is only relevant when qualifying a
228      constructor/destructor.  */
229   const char *set_last_name;
230   /* The length of set_last_name.  */
231   int set_last_name_len;
232 };
233
234 /* Accessors for subtrees of struct demangle_component.  */
235
236 #define d_left(dc) ((dc)->u.s_binary.left)
237 #define d_right(dc) ((dc)->u.s_binary.right)
238
239 /* A list of templates.  This is used while printing.  */
240
241 struct d_print_template
242 {
243   /* Next template on the list.  */
244   struct d_print_template *next;
245   /* This template.  */
246   const struct demangle_component *template_decl;
247 };
248
249 /* A list of type modifiers.  This is used while printing.  */
250
251 struct d_print_mod
252 {
253   /* Next modifier on the list.  These are in the reverse of the order
254      in which they appeared in the mangled string.  */
255   struct d_print_mod *next;
256   /* The modifier.  */
257   const struct demangle_component *mod;
258   /* Whether this modifier was printed.  */
259   int printed;
260   /* The list of templates which applies to this modifier.  */
261   struct d_print_template *templates;
262 };
263
264 /* We use these structures to hold information during printing.  */
265
266 struct d_growable_string
267 {
268   /* Buffer holding the result.  */
269   char *buf;
270   /* Current length of data in buffer.  */
271   size_t len;
272   /* Allocated size of buffer.  */
273   size_t alc;
274   /* Set to 1 if we had a memory allocation failure.  */
275   int allocation_failure;
276 };
277
278 /* A demangle component and some scope captured when it was first
279    traversed.  */
280
281 struct d_saved_scope
282 {
283   /* The component whose scope this is.  */
284   const struct demangle_component *container;
285   /* The list of templates, if any, that was current when this
286      scope was captured.  */
287   struct d_print_template *templates;
288 };
289
290 /* Checkpoint structure to allow backtracking.  This holds copies
291    of the fields of struct d_info that need to be restored
292    if a trial parse needs to be backtracked over.  */
293
294 struct d_info_checkpoint
295 {
296   const char *n;
297   int next_comp;
298   int next_sub;
299   int did_subs;
300   int expansion;
301 };
302
303 enum { D_PRINT_BUFFER_LENGTH = 256 };
304 struct d_print_info
305 {
306   /* Fixed-length allocated buffer for demangled data, flushed to the
307      callback with a NUL termination once full.  */
308   char buf[D_PRINT_BUFFER_LENGTH];
309   /* Current length of data in buffer.  */
310   size_t len;
311   /* The last character printed, saved individually so that it survives
312      any buffer flush.  */
313   char last_char;
314   /* Callback function to handle demangled buffer flush.  */
315   demangle_callbackref callback;
316   /* Opaque callback argument.  */
317   void *opaque;
318   /* The current list of templates, if any.  */
319   struct d_print_template *templates;
320   /* The current list of modifiers (e.g., pointer, reference, etc.),
321      if any.  */
322   struct d_print_mod *modifiers;
323   /* Set to 1 if we saw a demangling error.  */
324   int demangle_failure;
325   /* The current index into any template argument packs we are using
326      for printing.  */
327   int pack_index;
328   /* Number of d_print_flush calls so far.  */
329   unsigned long int flush_count;
330   /* Array of saved scopes for evaluating substitutions.  */
331   struct d_saved_scope *saved_scopes;
332   /* Index of the next unused saved scope in the above array.  */
333   int next_saved_scope;
334   /* Number of saved scopes in the above array.  */
335   int num_saved_scopes;
336   /* Array of templates for saving into scopes.  */
337   struct d_print_template *copy_templates;
338   /* Index of the next unused copy template in the above array.  */
339   int next_copy_template;
340   /* Number of copy templates in the above array.  */
341   int num_copy_templates;
342   /* The nearest enclosing template, if any.  */
343   const struct demangle_component *current_template;
344 };
345
346 #ifdef CP_DEMANGLE_DEBUG
347 static void d_dump (struct demangle_component *, int);
348 #endif
349
350 static struct demangle_component *
351 d_make_empty (struct d_info *);
352
353 static struct demangle_component *
354 d_make_comp (struct d_info *, enum demangle_component_type,
355              struct demangle_component *,
356              struct demangle_component *);
357
358 static struct demangle_component *
359 d_make_name (struct d_info *, const char *, int);
360
361 static struct demangle_component *
362 d_make_demangle_mangled_name (struct d_info *, const char *);
363
364 static struct demangle_component *
365 d_make_builtin_type (struct d_info *,
366                      const struct demangle_builtin_type_info *);
367
368 static struct demangle_component *
369 d_make_operator (struct d_info *,
370                  const struct demangle_operator_info *);
371
372 static struct demangle_component *
373 d_make_extended_operator (struct d_info *, int,
374                           struct demangle_component *);
375
376 static struct demangle_component *
377 d_make_ctor (struct d_info *, enum gnu_v3_ctor_kinds,
378              struct demangle_component *);
379
380 static struct demangle_component *
381 d_make_dtor (struct d_info *, enum gnu_v3_dtor_kinds,
382              struct demangle_component *);
383
384 static struct demangle_component *
385 d_make_template_param (struct d_info *, long);
386
387 static struct demangle_component *
388 d_make_sub (struct d_info *, const char *, int);
389
390 static int
391 has_return_type (struct demangle_component *);
392
393 static int
394 is_ctor_dtor_or_conversion (struct demangle_component *);
395
396 static struct demangle_component *d_encoding (struct d_info *, int);
397
398 static struct demangle_component *d_name (struct d_info *);
399
400 static struct demangle_component *d_nested_name (struct d_info *);
401
402 static struct demangle_component *d_prefix (struct d_info *);
403
404 static struct demangle_component *d_unqualified_name (struct d_info *);
405
406 static struct demangle_component *d_source_name (struct d_info *);
407
408 static long d_number (struct d_info *);
409
410 static struct demangle_component *d_identifier (struct d_info *, int);
411
412 static struct demangle_component *d_operator_name (struct d_info *);
413
414 static struct demangle_component *d_special_name (struct d_info *);
415
416 static int d_call_offset (struct d_info *, int);
417
418 static struct demangle_component *d_ctor_dtor_name (struct d_info *);
419
420 static struct demangle_component **
421 d_cv_qualifiers (struct d_info *, struct demangle_component **, int);
422
423 static struct demangle_component *
424 d_ref_qualifier (struct d_info *, struct demangle_component *);
425
426 static struct demangle_component *
427 d_function_type (struct d_info *);
428
429 static struct demangle_component *
430 d_bare_function_type (struct d_info *, int);
431
432 static struct demangle_component *
433 d_class_enum_type (struct d_info *);
434
435 static struct demangle_component *d_array_type (struct d_info *);
436
437 static struct demangle_component *d_vector_type (struct d_info *);
438
439 static struct demangle_component *
440 d_pointer_to_member_type (struct d_info *);
441
442 static struct demangle_component *
443 d_template_param (struct d_info *);
444
445 static struct demangle_component *d_template_args (struct d_info *);
446
447 static struct demangle_component *
448 d_template_arg (struct d_info *);
449
450 static struct demangle_component *d_expression (struct d_info *);
451
452 static struct demangle_component *d_expr_primary (struct d_info *);
453
454 static struct demangle_component *d_local_name (struct d_info *);
455
456 static int d_discriminator (struct d_info *);
457
458 static struct demangle_component *d_lambda (struct d_info *);
459
460 static struct demangle_component *d_unnamed_type (struct d_info *);
461
462 static struct demangle_component *
463 d_clone_suffix (struct d_info *, struct demangle_component *);
464
465 static int
466 d_add_substitution (struct d_info *, struct demangle_component *);
467
468 static struct demangle_component *d_substitution (struct d_info *, int);
469
470 static void d_checkpoint (struct d_info *, struct d_info_checkpoint *);
471
472 static void d_backtrack (struct d_info *, struct d_info_checkpoint *);
473
474 static void d_growable_string_init (struct d_growable_string *, size_t);
475
476 static inline void
477 d_growable_string_resize (struct d_growable_string *, size_t);
478
479 static inline void
480 d_growable_string_append_buffer (struct d_growable_string *,
481                                  const char *, size_t);
482 static void
483 d_growable_string_callback_adapter (const char *, size_t, void *);
484
485 static void
486 d_print_init (struct d_print_info *, demangle_callbackref, void *,
487               const struct demangle_component *);
488
489 static inline void d_print_error (struct d_print_info *);
490
491 static inline int d_print_saw_error (struct d_print_info *);
492
493 static inline void d_print_flush (struct d_print_info *);
494
495 static inline void d_append_char (struct d_print_info *, char);
496
497 static inline void d_append_buffer (struct d_print_info *,
498                                     const char *, size_t);
499
500 static inline void d_append_string (struct d_print_info *, const char *);
501
502 static inline char d_last_char (struct d_print_info *);
503
504 static void
505 d_print_comp (struct d_print_info *, int, const struct demangle_component *);
506
507 static void
508 d_print_java_identifier (struct d_print_info *, const char *, int);
509
510 static void
511 d_print_mod_list (struct d_print_info *, int, struct d_print_mod *, int);
512
513 static void
514 d_print_mod (struct d_print_info *, int, const struct demangle_component *);
515
516 static void
517 d_print_function_type (struct d_print_info *, int,
518                        const struct demangle_component *,
519                        struct d_print_mod *);
520
521 static void
522 d_print_array_type (struct d_print_info *, int,
523                     const struct demangle_component *,
524                     struct d_print_mod *);
525
526 static void
527 d_print_expr_op (struct d_print_info *, int, const struct demangle_component *);
528
529 static void
530 d_print_cast (struct d_print_info *, int, const struct demangle_component *);
531
532 static int d_demangle_callback (const char *, int,
533                                 demangle_callbackref, void *);
534 static char *d_demangle (const char *, int, size_t *);
535
536 #ifdef CP_DEMANGLE_DEBUG
537
538 static void
539 d_dump (struct demangle_component *dc, int indent)
540 {
541   int i;
542
543   if (dc == NULL)
544     {
545       if (indent == 0)
546         printf ("failed demangling\n");
547       return;
548     }
549
550   for (i = 0; i < indent; ++i)
551     putchar (' ');
552
553   switch (dc->type)
554     {
555     case DEMANGLE_COMPONENT_NAME:
556       printf ("name '%.*s'\n", dc->u.s_name.len, dc->u.s_name.s);
557       return;
558     case DEMANGLE_COMPONENT_TAGGED_NAME:
559       printf ("tagged name\n");
560       d_dump (dc->u.s_binary.left, indent + 2);
561       d_dump (dc->u.s_binary.right, indent + 2);
562       return;
563     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
564       printf ("template parameter %ld\n", dc->u.s_number.number);
565       return;
566     case DEMANGLE_COMPONENT_CTOR:
567       printf ("constructor %d\n", (int) dc->u.s_ctor.kind);
568       d_dump (dc->u.s_ctor.name, indent + 2);
569       return;
570     case DEMANGLE_COMPONENT_DTOR:
571       printf ("destructor %d\n", (int) dc->u.s_dtor.kind);
572       d_dump (dc->u.s_dtor.name, indent + 2);
573       return;
574     case DEMANGLE_COMPONENT_SUB_STD:
575       printf ("standard substitution %s\n", dc->u.s_string.string);
576       return;
577     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
578       printf ("builtin type %s\n", dc->u.s_builtin.type->name);
579       return;
580     case DEMANGLE_COMPONENT_OPERATOR:
581       printf ("operator %s\n", dc->u.s_operator.op->name);
582       return;
583     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
584       printf ("extended operator with %d args\n",
585               dc->u.s_extended_operator.args);
586       d_dump (dc->u.s_extended_operator.name, indent + 2);
587       return;
588
589     case DEMANGLE_COMPONENT_QUAL_NAME:
590       printf ("qualified name\n");
591       break;
592     case DEMANGLE_COMPONENT_LOCAL_NAME:
593       printf ("local name\n");
594       break;
595     case DEMANGLE_COMPONENT_TYPED_NAME:
596       printf ("typed name\n");
597       break;
598     case DEMANGLE_COMPONENT_TEMPLATE:
599       printf ("template\n");
600       break;
601     case DEMANGLE_COMPONENT_VTABLE:
602       printf ("vtable\n");
603       break;
604     case DEMANGLE_COMPONENT_VTT:
605       printf ("VTT\n");
606       break;
607     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
608       printf ("construction vtable\n");
609       break;
610     case DEMANGLE_COMPONENT_TYPEINFO:
611       printf ("typeinfo\n");
612       break;
613     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
614       printf ("typeinfo name\n");
615       break;
616     case DEMANGLE_COMPONENT_TYPEINFO_FN:
617       printf ("typeinfo function\n");
618       break;
619     case DEMANGLE_COMPONENT_THUNK:
620       printf ("thunk\n");
621       break;
622     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
623       printf ("virtual thunk\n");
624       break;
625     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
626       printf ("covariant thunk\n");
627       break;
628     case DEMANGLE_COMPONENT_JAVA_CLASS:
629       printf ("java class\n");
630       break;
631     case DEMANGLE_COMPONENT_GUARD:
632       printf ("guard\n");
633       break;
634     case DEMANGLE_COMPONENT_REFTEMP:
635       printf ("reference temporary\n");
636       break;
637     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
638       printf ("hidden alias\n");
639       break;
640     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
641       printf ("transaction clone\n");
642       break;
643     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
644       printf ("non-transaction clone\n");
645       break;
646     case DEMANGLE_COMPONENT_RESTRICT:
647       printf ("restrict\n");
648       break;
649     case DEMANGLE_COMPONENT_VOLATILE:
650       printf ("volatile\n");
651       break;
652     case DEMANGLE_COMPONENT_CONST:
653       printf ("const\n");
654       break;
655     case DEMANGLE_COMPONENT_RESTRICT_THIS:
656       printf ("restrict this\n");
657       break;
658     case DEMANGLE_COMPONENT_VOLATILE_THIS:
659       printf ("volatile this\n");
660       break;
661     case DEMANGLE_COMPONENT_CONST_THIS:
662       printf ("const this\n");
663       break;
664     case DEMANGLE_COMPONENT_REFERENCE_THIS:
665       printf ("reference this\n");
666       break;
667     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
668       printf ("rvalue reference this\n");
669       break;
670     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
671       printf ("vendor type qualifier\n");
672       break;
673     case DEMANGLE_COMPONENT_POINTER:
674       printf ("pointer\n");
675       break;
676     case DEMANGLE_COMPONENT_REFERENCE:
677       printf ("reference\n");
678       break;
679     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
680       printf ("rvalue reference\n");
681       break;
682     case DEMANGLE_COMPONENT_COMPLEX:
683       printf ("complex\n");
684       break;
685     case DEMANGLE_COMPONENT_IMAGINARY:
686       printf ("imaginary\n");
687       break;
688     case DEMANGLE_COMPONENT_VENDOR_TYPE:
689       printf ("vendor type\n");
690       break;
691     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
692       printf ("function type\n");
693       break;
694     case DEMANGLE_COMPONENT_ARRAY_TYPE:
695       printf ("array type\n");
696       break;
697     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
698       printf ("pointer to member type\n");
699       break;
700     case DEMANGLE_COMPONENT_FIXED_TYPE:
701       printf ("fixed-point type\n");
702       break;
703     case DEMANGLE_COMPONENT_ARGLIST:
704       printf ("argument list\n");
705       break;
706     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
707       printf ("template argument list\n");
708       break;
709     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
710       printf ("initializer list\n");
711       break;
712     case DEMANGLE_COMPONENT_CAST:
713       printf ("cast\n");
714       break;
715     case DEMANGLE_COMPONENT_NULLARY:
716       printf ("nullary operator\n");
717       break;
718     case DEMANGLE_COMPONENT_UNARY:
719       printf ("unary operator\n");
720       break;
721     case DEMANGLE_COMPONENT_BINARY:
722       printf ("binary operator\n");
723       break;
724     case DEMANGLE_COMPONENT_BINARY_ARGS:
725       printf ("binary operator arguments\n");
726       break;
727     case DEMANGLE_COMPONENT_TRINARY:
728       printf ("trinary operator\n");
729       break;
730     case DEMANGLE_COMPONENT_TRINARY_ARG1:
731       printf ("trinary operator arguments 1\n");
732       break;
733     case DEMANGLE_COMPONENT_TRINARY_ARG2:
734       printf ("trinary operator arguments 1\n");
735       break;
736     case DEMANGLE_COMPONENT_LITERAL:
737       printf ("literal\n");
738       break;
739     case DEMANGLE_COMPONENT_LITERAL_NEG:
740       printf ("negative literal\n");
741       break;
742     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
743       printf ("java resource\n");
744       break;
745     case DEMANGLE_COMPONENT_COMPOUND_NAME:
746       printf ("compound name\n");
747       break;
748     case DEMANGLE_COMPONENT_CHARACTER:
749       printf ("character '%c'\n",  dc->u.s_character.character);
750       return;
751     case DEMANGLE_COMPONENT_DECLTYPE:
752       printf ("decltype\n");
753       break;
754     case DEMANGLE_COMPONENT_PACK_EXPANSION:
755       printf ("pack expansion\n");
756       break;
757     case DEMANGLE_COMPONENT_TLS_INIT:
758       printf ("tls init function\n");
759       break;
760     case DEMANGLE_COMPONENT_TLS_WRAPPER:
761       printf ("tls wrapper function\n");
762       break;
763     case DEMANGLE_COMPONENT_DEFAULT_ARG:
764       printf ("default argument %d\n", dc->u.s_unary_num.num);
765       d_dump (dc->u.s_unary_num.sub, indent+2);
766       return;
767     case DEMANGLE_COMPONENT_LAMBDA:
768       printf ("lambda %d\n", dc->u.s_unary_num.num);
769       d_dump (dc->u.s_unary_num.sub, indent+2);
770       return;
771     }
772
773   d_dump (d_left (dc), indent + 2);
774   d_dump (d_right (dc), indent + 2);
775 }
776
777 #endif /* CP_DEMANGLE_DEBUG */
778
779 /* Fill in a DEMANGLE_COMPONENT_NAME.  */
780
781 CP_STATIC_IF_GLIBCPP_V3
782 int
783 cplus_demangle_fill_name (struct demangle_component *p, const char *s, int len)
784 {
785   if (p == NULL || s == NULL || len == 0)
786     return 0;
787   p->type = DEMANGLE_COMPONENT_NAME;
788   p->u.s_name.s = s;
789   p->u.s_name.len = len;
790   return 1;
791 }
792
793 /* Fill in a DEMANGLE_COMPONENT_EXTENDED_OPERATOR.  */
794
795 CP_STATIC_IF_GLIBCPP_V3
796 int
797 cplus_demangle_fill_extended_operator (struct demangle_component *p, int args,
798                                        struct demangle_component *name)
799 {
800   if (p == NULL || args < 0 || name == NULL)
801     return 0;
802   p->type = DEMANGLE_COMPONENT_EXTENDED_OPERATOR;
803   p->u.s_extended_operator.args = args;
804   p->u.s_extended_operator.name = name;
805   return 1;
806 }
807
808 /* Fill in a DEMANGLE_COMPONENT_CTOR.  */
809
810 CP_STATIC_IF_GLIBCPP_V3
811 int
812 cplus_demangle_fill_ctor (struct demangle_component *p,
813                           enum gnu_v3_ctor_kinds kind,
814                           struct demangle_component *name)
815 {
816   if (p == NULL
817       || name == NULL
818       || (int) kind < gnu_v3_complete_object_ctor
819       || (int) kind > gnu_v3_object_ctor_group)
820     return 0;
821   p->type = DEMANGLE_COMPONENT_CTOR;
822   p->u.s_ctor.kind = kind;
823   p->u.s_ctor.name = name;
824   return 1;
825 }
826
827 /* Fill in a DEMANGLE_COMPONENT_DTOR.  */
828
829 CP_STATIC_IF_GLIBCPP_V3
830 int
831 cplus_demangle_fill_dtor (struct demangle_component *p,
832                           enum gnu_v3_dtor_kinds kind,
833                           struct demangle_component *name)
834 {
835   if (p == NULL
836       || name == NULL
837       || (int) kind < gnu_v3_deleting_dtor
838       || (int) kind > gnu_v3_object_dtor_group)
839     return 0;
840   p->type = DEMANGLE_COMPONENT_DTOR;
841   p->u.s_dtor.kind = kind;
842   p->u.s_dtor.name = name;
843   return 1;
844 }
845
846 /* Add a new component.  */
847
848 static struct demangle_component *
849 d_make_empty (struct d_info *di)
850 {
851   struct demangle_component *p;
852
853   if (di->next_comp >= di->num_comps)
854     return NULL;
855   p = &di->comps[di->next_comp];
856   ++di->next_comp;
857   return p;
858 }
859
860 /* Add a new generic component.  */
861
862 static struct demangle_component *
863 d_make_comp (struct d_info *di, enum demangle_component_type type,
864              struct demangle_component *left,
865              struct demangle_component *right)
866 {
867   struct demangle_component *p;
868
869   /* We check for errors here.  A typical error would be a NULL return
870      from a subroutine.  We catch those here, and return NULL
871      upward.  */
872   switch (type)
873     {
874       /* These types require two parameters.  */
875     case DEMANGLE_COMPONENT_QUAL_NAME:
876     case DEMANGLE_COMPONENT_LOCAL_NAME:
877     case DEMANGLE_COMPONENT_TYPED_NAME:
878     case DEMANGLE_COMPONENT_TAGGED_NAME:
879     case DEMANGLE_COMPONENT_TEMPLATE:
880     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
881     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
882     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
883     case DEMANGLE_COMPONENT_UNARY:
884     case DEMANGLE_COMPONENT_BINARY:
885     case DEMANGLE_COMPONENT_BINARY_ARGS:
886     case DEMANGLE_COMPONENT_TRINARY:
887     case DEMANGLE_COMPONENT_TRINARY_ARG1:
888     case DEMANGLE_COMPONENT_LITERAL:
889     case DEMANGLE_COMPONENT_LITERAL_NEG:
890     case DEMANGLE_COMPONENT_COMPOUND_NAME:
891     case DEMANGLE_COMPONENT_VECTOR_TYPE:
892     case DEMANGLE_COMPONENT_CLONE:
893       if (left == NULL || right == NULL)
894         return NULL;
895       break;
896
897       /* These types only require one parameter.  */
898     case DEMANGLE_COMPONENT_VTABLE:
899     case DEMANGLE_COMPONENT_VTT:
900     case DEMANGLE_COMPONENT_TYPEINFO:
901     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
902     case DEMANGLE_COMPONENT_TYPEINFO_FN:
903     case DEMANGLE_COMPONENT_THUNK:
904     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
905     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
906     case DEMANGLE_COMPONENT_JAVA_CLASS:
907     case DEMANGLE_COMPONENT_GUARD:
908     case DEMANGLE_COMPONENT_TLS_INIT:
909     case DEMANGLE_COMPONENT_TLS_WRAPPER:
910     case DEMANGLE_COMPONENT_REFTEMP:
911     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
912     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
913     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
914     case DEMANGLE_COMPONENT_POINTER:
915     case DEMANGLE_COMPONENT_REFERENCE:
916     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
917     case DEMANGLE_COMPONENT_COMPLEX:
918     case DEMANGLE_COMPONENT_IMAGINARY:
919     case DEMANGLE_COMPONENT_VENDOR_TYPE:
920     case DEMANGLE_COMPONENT_CAST:
921     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
922     case DEMANGLE_COMPONENT_DECLTYPE:
923     case DEMANGLE_COMPONENT_PACK_EXPANSION:
924     case DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS:
925     case DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS:
926     case DEMANGLE_COMPONENT_NULLARY:
927     case DEMANGLE_COMPONENT_TRINARY_ARG2:
928       if (left == NULL)
929         return NULL;
930       break;
931
932       /* This needs a right parameter, but the left parameter can be
933          empty.  */
934     case DEMANGLE_COMPONENT_ARRAY_TYPE:
935     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
936       if (right == NULL)
937         return NULL;
938       break;
939
940       /* These are allowed to have no parameters--in some cases they
941          will be filled in later.  */
942     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
943     case DEMANGLE_COMPONENT_RESTRICT:
944     case DEMANGLE_COMPONENT_VOLATILE:
945     case DEMANGLE_COMPONENT_CONST:
946     case DEMANGLE_COMPONENT_RESTRICT_THIS:
947     case DEMANGLE_COMPONENT_VOLATILE_THIS:
948     case DEMANGLE_COMPONENT_CONST_THIS:
949     case DEMANGLE_COMPONENT_REFERENCE_THIS:
950     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
951     case DEMANGLE_COMPONENT_ARGLIST:
952     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
953       break;
954
955       /* Other types should not be seen here.  */
956     default:
957       return NULL;
958     }
959
960   p = d_make_empty (di);
961   if (p != NULL)
962     {
963       p->type = type;
964       p->u.s_binary.left = left;
965       p->u.s_binary.right = right;
966     }
967   return p;
968 }
969
970 /* Add a new demangle mangled name component.  */
971
972 static struct demangle_component *
973 d_make_demangle_mangled_name (struct d_info *di, const char *s)
974 {
975   if (d_peek_char (di) != '_' || d_peek_next_char (di) != 'Z')
976     return d_make_name (di, s, strlen (s));
977   d_advance (di, 2);
978   return d_encoding (di, 0);
979 }
980
981 /* Add a new name component.  */
982
983 static struct demangle_component *
984 d_make_name (struct d_info *di, const char *s, int len)
985 {
986   struct demangle_component *p;
987
988   p = d_make_empty (di);
989   if (! cplus_demangle_fill_name (p, s, len))
990     return NULL;
991   return p;
992 }
993
994 /* Add a new builtin type component.  */
995
996 static struct demangle_component *
997 d_make_builtin_type (struct d_info *di,
998                      const struct demangle_builtin_type_info *type)
999 {
1000   struct demangle_component *p;
1001
1002   if (type == NULL)
1003     return NULL;
1004   p = d_make_empty (di);
1005   if (p != NULL)
1006     {
1007       p->type = DEMANGLE_COMPONENT_BUILTIN_TYPE;
1008       p->u.s_builtin.type = type;
1009     }
1010   return p;
1011 }
1012
1013 /* Add a new operator component.  */
1014
1015 static struct demangle_component *
1016 d_make_operator (struct d_info *di, const struct demangle_operator_info *op)
1017 {
1018   struct demangle_component *p;
1019
1020   p = d_make_empty (di);
1021   if (p != NULL)
1022     {
1023       p->type = DEMANGLE_COMPONENT_OPERATOR;
1024       p->u.s_operator.op = op;
1025     }
1026   return p;
1027 }
1028
1029 /* Add a new extended operator component.  */
1030
1031 static struct demangle_component *
1032 d_make_extended_operator (struct d_info *di, int args,
1033                           struct demangle_component *name)
1034 {
1035   struct demangle_component *p;
1036
1037   p = d_make_empty (di);
1038   if (! cplus_demangle_fill_extended_operator (p, args, name))
1039     return NULL;
1040   return p;
1041 }
1042
1043 static struct demangle_component *
1044 d_make_default_arg (struct d_info *di, int num,
1045                     struct demangle_component *sub)
1046 {
1047   struct demangle_component *p = d_make_empty (di);
1048   if (p)
1049     {
1050       p->type = DEMANGLE_COMPONENT_DEFAULT_ARG;
1051       p->u.s_unary_num.num = num;
1052       p->u.s_unary_num.sub = sub;
1053     }
1054   return p;
1055 }
1056
1057 /* Add a new constructor component.  */
1058
1059 static struct demangle_component *
1060 d_make_ctor (struct d_info *di, enum gnu_v3_ctor_kinds kind,
1061              struct demangle_component *name)
1062 {
1063   struct demangle_component *p;
1064
1065   p = d_make_empty (di);
1066   if (! cplus_demangle_fill_ctor (p, kind, name))
1067     return NULL;
1068   return p;
1069 }
1070
1071 /* Add a new destructor component.  */
1072
1073 static struct demangle_component *
1074 d_make_dtor (struct d_info *di, enum gnu_v3_dtor_kinds kind,
1075              struct demangle_component *name)
1076 {
1077   struct demangle_component *p;
1078
1079   p = d_make_empty (di);
1080   if (! cplus_demangle_fill_dtor (p, kind, name))
1081     return NULL;
1082   return p;
1083 }
1084
1085 /* Add a new template parameter.  */
1086
1087 static struct demangle_component *
1088 d_make_template_param (struct d_info *di, long i)
1089 {
1090   struct demangle_component *p;
1091
1092   p = d_make_empty (di);
1093   if (p != NULL)
1094     {
1095       p->type = DEMANGLE_COMPONENT_TEMPLATE_PARAM;
1096       p->u.s_number.number = i;
1097     }
1098   return p;
1099 }
1100
1101 /* Add a new function parameter.  */
1102
1103 static struct demangle_component *
1104 d_make_function_param (struct d_info *di, long i)
1105 {
1106   struct demangle_component *p;
1107
1108   p = d_make_empty (di);
1109   if (p != NULL)
1110     {
1111       p->type = DEMANGLE_COMPONENT_FUNCTION_PARAM;
1112       p->u.s_number.number = i;
1113     }
1114   return p;
1115 }
1116
1117 /* Add a new standard substitution component.  */
1118
1119 static struct demangle_component *
1120 d_make_sub (struct d_info *di, const char *name, int len)
1121 {
1122   struct demangle_component *p;
1123
1124   p = d_make_empty (di);
1125   if (p != NULL)
1126     {
1127       p->type = DEMANGLE_COMPONENT_SUB_STD;
1128       p->u.s_string.string = name;
1129       p->u.s_string.len = len;
1130     }
1131   return p;
1132 }
1133
1134 /* <mangled-name> ::= _Z <encoding> [<clone-suffix>]*
1135
1136    TOP_LEVEL is non-zero when called at the top level.  */
1137
1138 CP_STATIC_IF_GLIBCPP_V3
1139 struct demangle_component *
1140 cplus_demangle_mangled_name (struct d_info *di, int top_level)
1141 {
1142   struct demangle_component *p;
1143
1144   if (! d_check_char (di, '_')
1145       /* Allow missing _ if not at toplevel to work around a
1146          bug in G++ abi-version=2 mangling; see the comment in
1147          write_template_arg.  */
1148       && top_level)
1149     return NULL;
1150   if (! d_check_char (di, 'Z'))
1151     return NULL;
1152   p = d_encoding (di, top_level);
1153
1154   /* If at top level and parsing parameters, check for a clone
1155      suffix.  */
1156   if (top_level && (di->options & DMGL_PARAMS) != 0)
1157     while (d_peek_char (di) == '.'
1158            && (IS_LOWER (d_peek_next_char (di))
1159                || d_peek_next_char (di) == '_'
1160                || IS_DIGIT (d_peek_next_char (di))))
1161       p = d_clone_suffix (di, p);
1162
1163   return p;
1164 }
1165
1166 /* Return whether a function should have a return type.  The argument
1167    is the function name, which may be qualified in various ways.  The
1168    rules are that template functions have return types with some
1169    exceptions, function types which are not part of a function name
1170    mangling have return types with some exceptions, and non-template
1171    function names do not have return types.  The exceptions are that
1172    constructors, destructors, and conversion operators do not have
1173    return types.  */
1174
1175 static int
1176 has_return_type (struct demangle_component *dc)
1177 {
1178   if (dc == NULL)
1179     return 0;
1180   switch (dc->type)
1181     {
1182     default:
1183       return 0;
1184     case DEMANGLE_COMPONENT_TEMPLATE:
1185       return ! is_ctor_dtor_or_conversion (d_left (dc));
1186     case DEMANGLE_COMPONENT_RESTRICT_THIS:
1187     case DEMANGLE_COMPONENT_VOLATILE_THIS:
1188     case DEMANGLE_COMPONENT_CONST_THIS:
1189     case DEMANGLE_COMPONENT_REFERENCE_THIS:
1190     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
1191       return has_return_type (d_left (dc));
1192     }
1193 }
1194
1195 /* Return whether a name is a constructor, a destructor, or a
1196    conversion operator.  */
1197
1198 static int
1199 is_ctor_dtor_or_conversion (struct demangle_component *dc)
1200 {
1201   if (dc == NULL)
1202     return 0;
1203   switch (dc->type)
1204     {
1205     default:
1206       return 0;
1207     case DEMANGLE_COMPONENT_QUAL_NAME:
1208     case DEMANGLE_COMPONENT_LOCAL_NAME:
1209       return is_ctor_dtor_or_conversion (d_right (dc));
1210     case DEMANGLE_COMPONENT_CTOR:
1211     case DEMANGLE_COMPONENT_DTOR:
1212     case DEMANGLE_COMPONENT_CAST:
1213       return 1;
1214     }
1215 }
1216
1217 /* <encoding> ::= <(function) name> <bare-function-type>
1218               ::= <(data) name>
1219               ::= <special-name>
1220
1221    TOP_LEVEL is non-zero when called at the top level, in which case
1222    if DMGL_PARAMS is not set we do not demangle the function
1223    parameters.  We only set this at the top level, because otherwise
1224    we would not correctly demangle names in local scopes.  */
1225
1226 static struct demangle_component *
1227 d_encoding (struct d_info *di, int top_level)
1228 {
1229   char peek = d_peek_char (di);
1230
1231   if (peek == 'G' || peek == 'T')
1232     return d_special_name (di);
1233   else
1234     {
1235       struct demangle_component *dc;
1236
1237       dc = d_name (di);
1238
1239       if (dc != NULL && top_level && (di->options & DMGL_PARAMS) == 0)
1240         {
1241           /* Strip off any initial CV-qualifiers, as they really apply
1242              to the `this' parameter, and they were not output by the
1243              v2 demangler without DMGL_PARAMS.  */
1244           while (dc->type == DEMANGLE_COMPONENT_RESTRICT_THIS
1245                  || dc->type == DEMANGLE_COMPONENT_VOLATILE_THIS
1246                  || dc->type == DEMANGLE_COMPONENT_CONST_THIS
1247                  || dc->type == DEMANGLE_COMPONENT_REFERENCE_THIS
1248                  || dc->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS)
1249             dc = d_left (dc);
1250
1251           /* If the top level is a DEMANGLE_COMPONENT_LOCAL_NAME, then
1252              there may be CV-qualifiers on its right argument which
1253              really apply here; this happens when parsing a class
1254              which is local to a function.  */
1255           if (dc->type == DEMANGLE_COMPONENT_LOCAL_NAME)
1256             {
1257               struct demangle_component *dcr;
1258
1259               dcr = d_right (dc);
1260               while (dcr->type == DEMANGLE_COMPONENT_RESTRICT_THIS
1261                      || dcr->type == DEMANGLE_COMPONENT_VOLATILE_THIS
1262                      || dcr->type == DEMANGLE_COMPONENT_CONST_THIS
1263                      || dcr->type == DEMANGLE_COMPONENT_REFERENCE_THIS
1264                      || dcr->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS)
1265                 dcr = d_left (dcr);
1266               dc->u.s_binary.right = dcr;
1267             }
1268
1269           return dc;
1270         }
1271
1272       peek = d_peek_char (di);
1273       if (dc == NULL || peek == '\0' || peek == 'E')
1274         return dc;
1275       return d_make_comp (di, DEMANGLE_COMPONENT_TYPED_NAME, dc,
1276                           d_bare_function_type (di, has_return_type (dc)));
1277     }
1278 }
1279
1280 /* <tagged-name> ::= <name> B <source-name> */
1281
1282 static struct demangle_component *
1283 d_abi_tags (struct d_info *di, struct demangle_component *dc)
1284 {
1285   char peek;
1286   while (peek = d_peek_char (di),
1287          peek == 'B')
1288     {
1289       struct demangle_component *tag;
1290       d_advance (di, 1);
1291       tag = d_source_name (di);
1292       dc = d_make_comp (di, DEMANGLE_COMPONENT_TAGGED_NAME, dc, tag);
1293     }
1294   return dc;
1295 }
1296
1297 /* <name> ::= <nested-name>
1298           ::= <unscoped-name>
1299           ::= <unscoped-template-name> <template-args>
1300           ::= <local-name>
1301
1302    <unscoped-name> ::= <unqualified-name>
1303                    ::= St <unqualified-name>
1304
1305    <unscoped-template-name> ::= <unscoped-name>
1306                             ::= <substitution>
1307 */
1308
1309 static struct demangle_component *
1310 d_name (struct d_info *di)
1311 {
1312   char peek = d_peek_char (di);
1313   struct demangle_component *dc;
1314
1315   switch (peek)
1316     {
1317     case 'N':
1318       return d_nested_name (di);
1319
1320     case 'Z':
1321       return d_local_name (di);
1322
1323     case 'U':
1324       return d_unqualified_name (di);
1325
1326     case 'S':
1327       {
1328         int subst;
1329
1330         if (d_peek_next_char (di) != 't')
1331           {
1332             dc = d_substitution (di, 0);
1333             subst = 1;
1334           }
1335         else
1336           {
1337             d_advance (di, 2);
1338             dc = d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME,
1339                               d_make_name (di, "std", 3),
1340                               d_unqualified_name (di));
1341             di->expansion += 3;
1342             subst = 0;
1343           }
1344
1345         if (d_peek_char (di) != 'I')
1346           {
1347             /* The grammar does not permit this case to occur if we
1348                called d_substitution() above (i.e., subst == 1).  We
1349                don't bother to check.  */
1350           }
1351         else
1352           {
1353             /* This is <template-args>, which means that we just saw
1354                <unscoped-template-name>, which is a substitution
1355                candidate if we didn't just get it from a
1356                substitution.  */
1357             if (! subst)
1358               {
1359                 if (! d_add_substitution (di, dc))
1360                   return NULL;
1361               }
1362             dc = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, dc,
1363                               d_template_args (di));
1364           }
1365
1366         return dc;
1367       }
1368
1369     case 'L':
1370     default:
1371       dc = d_unqualified_name (di);
1372       if (d_peek_char (di) == 'I')
1373         {
1374           /* This is <template-args>, which means that we just saw
1375              <unscoped-template-name>, which is a substitution
1376              candidate.  */
1377           if (! d_add_substitution (di, dc))
1378             return NULL;
1379           dc = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, dc,
1380                             d_template_args (di));
1381         }
1382       return dc;
1383     }
1384 }
1385
1386 /* <nested-name> ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1387                  ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
1388 */
1389
1390 static struct demangle_component *
1391 d_nested_name (struct d_info *di)
1392 {
1393   struct demangle_component *ret;
1394   struct demangle_component **pret;
1395   struct demangle_component *rqual;
1396
1397   if (! d_check_char (di, 'N'))
1398     return NULL;
1399
1400   pret = d_cv_qualifiers (di, &ret, 1);
1401   if (pret == NULL)
1402     return NULL;
1403
1404   /* Parse the ref-qualifier now and then attach it
1405      once we have something to attach it to.  */
1406   rqual = d_ref_qualifier (di, NULL);
1407
1408   *pret = d_prefix (di);
1409   if (*pret == NULL)
1410     return NULL;
1411
1412   if (rqual)
1413     {
1414       d_left (rqual) = ret;
1415       ret = rqual;
1416     }
1417
1418   if (! d_check_char (di, 'E'))
1419     return NULL;
1420
1421   return ret;
1422 }
1423
1424 /* <prefix> ::= <prefix> <unqualified-name>
1425             ::= <template-prefix> <template-args>
1426             ::= <template-param>
1427             ::= <decltype>
1428             ::=
1429             ::= <substitution>
1430
1431    <template-prefix> ::= <prefix> <(template) unqualified-name>
1432                      ::= <template-param>
1433                      ::= <substitution>
1434 */
1435
1436 static struct demangle_component *
1437 d_prefix (struct d_info *di)
1438 {
1439   struct demangle_component *ret = NULL;
1440
1441   while (1)
1442     {
1443       char peek;
1444       enum demangle_component_type comb_type;
1445       struct demangle_component *dc;
1446
1447       peek = d_peek_char (di);
1448       if (peek == '\0')
1449         return NULL;
1450
1451       /* The older code accepts a <local-name> here, but I don't see
1452          that in the grammar.  The older code does not accept a
1453          <template-param> here.  */
1454
1455       comb_type = DEMANGLE_COMPONENT_QUAL_NAME;
1456       if (peek == 'D')
1457         {
1458           char peek2 = d_peek_next_char (di);
1459           if (peek2 == 'T' || peek2 == 't')
1460             /* Decltype.  */
1461             dc = cplus_demangle_type (di);
1462           else
1463             /* Destructor name.  */
1464             dc = d_unqualified_name (di);
1465         }
1466       else if (IS_DIGIT (peek)
1467           || IS_LOWER (peek)
1468           || peek == 'C'
1469           || peek == 'U'
1470           || peek == 'L')
1471         dc = d_unqualified_name (di);
1472       else if (peek == 'S')
1473         dc = d_substitution (di, 1);
1474       else if (peek == 'I')
1475         {
1476           if (ret == NULL)
1477             return NULL;
1478           comb_type = DEMANGLE_COMPONENT_TEMPLATE;
1479           dc = d_template_args (di);
1480         }
1481       else if (peek == 'T')
1482         dc = d_template_param (di);
1483       else if (peek == 'E')
1484         return ret;
1485       else if (peek == 'M')
1486         {
1487           /* Initializer scope for a lambda.  We don't need to represent
1488              this; the normal code will just treat the variable as a type
1489              scope, which gives appropriate output.  */
1490           if (ret == NULL)
1491             return NULL;
1492           d_advance (di, 1);
1493           continue;
1494         }
1495       else
1496         return NULL;
1497
1498       if (ret == NULL)
1499         ret = dc;
1500       else
1501         ret = d_make_comp (di, comb_type, ret, dc);
1502
1503       if (peek != 'S' && d_peek_char (di) != 'E')
1504         {
1505           if (! d_add_substitution (di, ret))
1506             return NULL;
1507         }
1508     }
1509 }
1510
1511 /* <unqualified-name> ::= <operator-name>
1512                       ::= <ctor-dtor-name>
1513                       ::= <source-name>
1514                       ::= <local-source-name> 
1515
1516     <local-source-name> ::= L <source-name> <discriminator>
1517 */
1518
1519 static struct demangle_component *
1520 d_unqualified_name (struct d_info *di)
1521 {
1522   struct demangle_component *ret;
1523   char peek;
1524
1525   peek = d_peek_char (di);
1526   if (IS_DIGIT (peek))
1527     ret = d_source_name (di);
1528   else if (IS_LOWER (peek))
1529     {
1530       ret = d_operator_name (di);
1531       if (ret != NULL && ret->type == DEMANGLE_COMPONENT_OPERATOR)
1532         {
1533           di->expansion += sizeof "operator" + ret->u.s_operator.op->len - 2;
1534           if (!strcmp (ret->u.s_operator.op->code, "li"))
1535             ret = d_make_comp (di, DEMANGLE_COMPONENT_UNARY, ret,
1536                                d_source_name (di));
1537         }
1538     }
1539   else if (peek == 'C' || peek == 'D')
1540     ret = d_ctor_dtor_name (di);
1541   else if (peek == 'L')
1542     {
1543       d_advance (di, 1);
1544
1545       ret = d_source_name (di);
1546       if (ret == NULL)
1547         return NULL;
1548       if (! d_discriminator (di))
1549         return NULL;
1550     }
1551   else if (peek == 'U')
1552     {
1553       switch (d_peek_next_char (di))
1554         {
1555         case 'l':
1556           ret = d_lambda (di);
1557           break;
1558         case 't':
1559           ret = d_unnamed_type (di);
1560           break;
1561         default:
1562           return NULL;
1563         }
1564     }
1565   else
1566     return NULL;
1567
1568   if (d_peek_char (di) == 'B')
1569     ret = d_abi_tags (di, ret);
1570   return ret;
1571 }
1572
1573 /* <source-name> ::= <(positive length) number> <identifier>  */
1574
1575 static struct demangle_component *
1576 d_source_name (struct d_info *di)
1577 {
1578   long len;
1579   struct demangle_component *ret;
1580
1581   len = d_number (di);
1582   if (len <= 0)
1583     return NULL;
1584   ret = d_identifier (di, len);
1585   di->last_name = ret;
1586   return ret;
1587 }
1588
1589 /* number ::= [n] <(non-negative decimal integer)>  */
1590
1591 static long
1592 d_number (struct d_info *di)
1593 {
1594   int negative;
1595   char peek;
1596   long ret;
1597
1598   negative = 0;
1599   peek = d_peek_char (di);
1600   if (peek == 'n')
1601     {
1602       negative = 1;
1603       d_advance (di, 1);
1604       peek = d_peek_char (di);
1605     }
1606
1607   ret = 0;
1608   while (1)
1609     {
1610       if (! IS_DIGIT (peek))
1611         {
1612           if (negative)
1613             ret = - ret;
1614           return ret;
1615         }
1616       ret = ret * 10 + peek - '0';
1617       d_advance (di, 1);
1618       peek = d_peek_char (di);
1619     }
1620 }
1621
1622 /* Like d_number, but returns a demangle_component.  */
1623
1624 static struct demangle_component *
1625 d_number_component (struct d_info *di)
1626 {
1627   struct demangle_component *ret = d_make_empty (di);
1628   if (ret)
1629     {
1630       ret->type = DEMANGLE_COMPONENT_NUMBER;
1631       ret->u.s_number.number = d_number (di);
1632     }
1633   return ret;
1634 }
1635
1636 /* identifier ::= <(unqualified source code identifier)>  */
1637
1638 static struct demangle_component *
1639 d_identifier (struct d_info *di, int len)
1640 {
1641   const char *name;
1642
1643   name = d_str (di);
1644
1645   if (di->send - name < len)
1646     return NULL;
1647
1648   d_advance (di, len);
1649
1650   /* A Java mangled name may have a trailing '$' if it is a C++
1651      keyword.  This '$' is not included in the length count.  We just
1652      ignore the '$'.  */
1653   if ((di->options & DMGL_JAVA) != 0
1654       && d_peek_char (di) == '$')
1655     d_advance (di, 1);
1656
1657   /* Look for something which looks like a gcc encoding of an
1658      anonymous namespace, and replace it with a more user friendly
1659      name.  */
1660   if (len >= (int) ANONYMOUS_NAMESPACE_PREFIX_LEN + 2
1661       && memcmp (name, ANONYMOUS_NAMESPACE_PREFIX,
1662                  ANONYMOUS_NAMESPACE_PREFIX_LEN) == 0)
1663     {
1664       const char *s;
1665
1666       s = name + ANONYMOUS_NAMESPACE_PREFIX_LEN;
1667       if ((*s == '.' || *s == '_' || *s == '$')
1668           && s[1] == 'N')
1669         {
1670           di->expansion -= len - sizeof "(anonymous namespace)";
1671           return d_make_name (di, "(anonymous namespace)",
1672                               sizeof "(anonymous namespace)" - 1);
1673         }
1674     }
1675
1676   return d_make_name (di, name, len);
1677 }
1678
1679 /* operator_name ::= many different two character encodings.
1680                  ::= cv <type>
1681                  ::= v <digit> <source-name>
1682
1683    This list is sorted for binary search.  */
1684
1685 #define NL(s) s, (sizeof s) - 1
1686
1687 CP_STATIC_IF_GLIBCPP_V3
1688 const struct demangle_operator_info cplus_demangle_operators[] =
1689 {
1690   { "aN", NL ("&="),        2 },
1691   { "aS", NL ("="),         2 },
1692   { "aa", NL ("&&"),        2 },
1693   { "ad", NL ("&"),         1 },
1694   { "an", NL ("&"),         2 },
1695   { "at", NL ("alignof "),   1 },
1696   { "az", NL ("alignof "),   1 },
1697   { "cc", NL ("const_cast"), 2 },
1698   { "cl", NL ("()"),        2 },
1699   { "cm", NL (","),         2 },
1700   { "co", NL ("~"),         1 },
1701   { "dV", NL ("/="),        2 },
1702   { "da", NL ("delete[] "), 1 },
1703   { "dc", NL ("dynamic_cast"), 2 },
1704   { "de", NL ("*"),         1 },
1705   { "dl", NL ("delete "),   1 },
1706   { "ds", NL (".*"),        2 },
1707   { "dt", NL ("."),         2 },
1708   { "dv", NL ("/"),         2 },
1709   { "eO", NL ("^="),        2 },
1710   { "eo", NL ("^"),         2 },
1711   { "eq", NL ("=="),        2 },
1712   { "ge", NL (">="),        2 },
1713   { "gs", NL ("::"),        1 },
1714   { "gt", NL (">"),         2 },
1715   { "ix", NL ("[]"),        2 },
1716   { "lS", NL ("<<="),       2 },
1717   { "le", NL ("<="),        2 },
1718   { "li", NL ("operator\"\" "), 1 },
1719   { "ls", NL ("<<"),        2 },
1720   { "lt", NL ("<"),         2 },
1721   { "mI", NL ("-="),        2 },
1722   { "mL", NL ("*="),        2 },
1723   { "mi", NL ("-"),         2 },
1724   { "ml", NL ("*"),         2 },
1725   { "mm", NL ("--"),        1 },
1726   { "na", NL ("new[]"),     3 },
1727   { "ne", NL ("!="),        2 },
1728   { "ng", NL ("-"),         1 },
1729   { "nt", NL ("!"),         1 },
1730   { "nw", NL ("new"),       3 },
1731   { "oR", NL ("|="),        2 },
1732   { "oo", NL ("||"),        2 },
1733   { "or", NL ("|"),         2 },
1734   { "pL", NL ("+="),        2 },
1735   { "pl", NL ("+"),         2 },
1736   { "pm", NL ("->*"),       2 },
1737   { "pp", NL ("++"),        1 },
1738   { "ps", NL ("+"),         1 },
1739   { "pt", NL ("->"),        2 },
1740   { "qu", NL ("?"),         3 },
1741   { "rM", NL ("%="),        2 },
1742   { "rS", NL (">>="),       2 },
1743   { "rc", NL ("reinterpret_cast"), 2 },
1744   { "rm", NL ("%"),         2 },
1745   { "rs", NL (">>"),        2 },
1746   { "sc", NL ("static_cast"), 2 },
1747   { "st", NL ("sizeof "),   1 },
1748   { "sz", NL ("sizeof "),   1 },
1749   { "tr", NL ("throw"),     0 },
1750   { "tw", NL ("throw "),    1 },
1751   { NULL, NULL, 0,          0 }
1752 };
1753
1754 static struct demangle_component *
1755 d_operator_name (struct d_info *di)
1756 {
1757   char c1;
1758   char c2;
1759
1760   c1 = d_next_char (di);
1761   c2 = d_next_char (di);
1762   if (c1 == 'v' && IS_DIGIT (c2))
1763     return d_make_extended_operator (di, c2 - '0', d_source_name (di));
1764   else if (c1 == 'c' && c2 == 'v')
1765     {
1766       struct demangle_component *type;
1767       int was_conversion = di->is_conversion;
1768
1769       di->is_conversion = ! di->is_expression;
1770       type = cplus_demangle_type (di);
1771       di->is_conversion = was_conversion;
1772       return d_make_comp (di, DEMANGLE_COMPONENT_CAST, type, NULL);
1773     }
1774   else
1775     {
1776       /* LOW is the inclusive lower bound.  */
1777       int low = 0;
1778       /* HIGH is the exclusive upper bound.  We subtract one to ignore
1779          the sentinel at the end of the array.  */
1780       int high = ((sizeof (cplus_demangle_operators)
1781                    / sizeof (cplus_demangle_operators[0]))
1782                   - 1);
1783
1784       while (1)
1785         {
1786           int i;
1787           const struct demangle_operator_info *p;
1788
1789           i = low + (high - low) / 2;
1790           p = cplus_demangle_operators + i;
1791
1792           if (c1 == p->code[0] && c2 == p->code[1])
1793             return d_make_operator (di, p);
1794
1795           if (c1 < p->code[0] || (c1 == p->code[0] && c2 < p->code[1]))
1796             high = i;
1797           else
1798             low = i + 1;
1799           if (low == high)
1800             return NULL;
1801         }
1802     }
1803 }
1804
1805 static struct demangle_component *
1806 d_make_character (struct d_info *di, int c)
1807 {
1808   struct demangle_component *p;
1809   p = d_make_empty (di);
1810   if (p != NULL)
1811     {
1812       p->type = DEMANGLE_COMPONENT_CHARACTER;
1813       p->u.s_character.character = c;
1814     }
1815   return p;
1816 }
1817
1818 static struct demangle_component *
1819 d_java_resource (struct d_info *di)
1820 {
1821   struct demangle_component *p = NULL;
1822   struct demangle_component *next = NULL;
1823   long len, i;
1824   char c;
1825   const char *str;
1826
1827   len = d_number (di);
1828   if (len <= 1)
1829     return NULL;
1830
1831   /* Eat the leading '_'.  */
1832   if (d_next_char (di) != '_')
1833     return NULL;
1834   len--;
1835
1836   str = d_str (di);
1837   i = 0;
1838
1839   while (len > 0)
1840     {
1841       c = str[i];
1842       if (!c)
1843         return NULL;
1844
1845       /* Each chunk is either a '$' escape...  */
1846       if (c == '$')
1847         {
1848           i++;
1849           switch (str[i++])
1850             {
1851             case 'S':
1852               c = '/';
1853               break;
1854             case '_':
1855               c = '.';
1856               break;
1857             case '$':
1858               c = '$';
1859               break;
1860             default:
1861               return NULL;
1862             }
1863           next = d_make_character (di, c);
1864           d_advance (di, i);
1865           str = d_str (di);
1866           len -= i;
1867           i = 0;
1868           if (next == NULL)
1869             return NULL;
1870         }
1871       /* ... or a sequence of characters.  */
1872       else
1873         {
1874           while (i < len && str[i] && str[i] != '$')
1875             i++;
1876
1877           next = d_make_name (di, str, i);
1878           d_advance (di, i);
1879           str = d_str (di);
1880           len -= i;
1881           i = 0;
1882           if (next == NULL)
1883             return NULL;
1884         }
1885
1886       if (p == NULL)
1887         p = next;
1888       else
1889         {
1890           p = d_make_comp (di, DEMANGLE_COMPONENT_COMPOUND_NAME, p, next);
1891           if (p == NULL)
1892             return NULL;
1893         }
1894     }
1895
1896   p = d_make_comp (di, DEMANGLE_COMPONENT_JAVA_RESOURCE, p, NULL);
1897
1898   return p;
1899 }
1900
1901 /* <special-name> ::= TV <type>
1902                   ::= TT <type>
1903                   ::= TI <type>
1904                   ::= TS <type>
1905                   ::= GV <(object) name>
1906                   ::= T <call-offset> <(base) encoding>
1907                   ::= Tc <call-offset> <call-offset> <(base) encoding>
1908    Also g++ extensions:
1909                   ::= TC <type> <(offset) number> _ <(base) type>
1910                   ::= TF <type>
1911                   ::= TJ <type>
1912                   ::= GR <name>
1913                   ::= GA <encoding>
1914                   ::= Gr <resource name>
1915                   ::= GTt <encoding>
1916                   ::= GTn <encoding>
1917 */
1918
1919 static struct demangle_component *
1920 d_special_name (struct d_info *di)
1921 {
1922   di->expansion += 20;
1923   if (d_check_char (di, 'T'))
1924     {
1925       switch (d_next_char (di))
1926         {
1927         case 'V':
1928           di->expansion -= 5;
1929           return d_make_comp (di, DEMANGLE_COMPONENT_VTABLE,
1930                               cplus_demangle_type (di), NULL);
1931         case 'T':
1932           di->expansion -= 10;
1933           return d_make_comp (di, DEMANGLE_COMPONENT_VTT,
1934                               cplus_demangle_type (di), NULL);
1935         case 'I':
1936           return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO,
1937                               cplus_demangle_type (di), NULL);
1938         case 'S':
1939           return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO_NAME,
1940                               cplus_demangle_type (di), NULL);
1941
1942         case 'h':
1943           if (! d_call_offset (di, 'h'))
1944             return NULL;
1945           return d_make_comp (di, DEMANGLE_COMPONENT_THUNK,
1946                               d_encoding (di, 0), NULL);
1947
1948         case 'v':
1949           if (! d_call_offset (di, 'v'))
1950             return NULL;
1951           return d_make_comp (di, DEMANGLE_COMPONENT_VIRTUAL_THUNK,
1952                               d_encoding (di, 0), NULL);
1953
1954         case 'c':
1955           if (! d_call_offset (di, '\0'))
1956             return NULL;
1957           if (! d_call_offset (di, '\0'))
1958             return NULL;
1959           return d_make_comp (di, DEMANGLE_COMPONENT_COVARIANT_THUNK,
1960                               d_encoding (di, 0), NULL);
1961
1962         case 'C':
1963           {
1964             struct demangle_component *derived_type;
1965             long offset;
1966             struct demangle_component *base_type;
1967
1968             derived_type = cplus_demangle_type (di);
1969             offset = d_number (di);
1970             if (offset < 0)
1971               return NULL;
1972             if (! d_check_char (di, '_'))
1973               return NULL;
1974             base_type = cplus_demangle_type (di);
1975             /* We don't display the offset.  FIXME: We should display
1976                it in verbose mode.  */
1977             di->expansion += 5;
1978             return d_make_comp (di, DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE,
1979                                 base_type, derived_type);
1980           }
1981
1982         case 'F':
1983           return d_make_comp (di, DEMANGLE_COMPONENT_TYPEINFO_FN,
1984                               cplus_demangle_type (di), NULL);
1985         case 'J':
1986           return d_make_comp (di, DEMANGLE_COMPONENT_JAVA_CLASS,
1987                               cplus_demangle_type (di), NULL);
1988
1989         case 'H':
1990           return d_make_comp (di, DEMANGLE_COMPONENT_TLS_INIT,
1991                               d_name (di), NULL);
1992
1993         case 'W':
1994           return d_make_comp (di, DEMANGLE_COMPONENT_TLS_WRAPPER,
1995                               d_name (di), NULL);
1996
1997         default:
1998           return NULL;
1999         }
2000     }
2001   else if (d_check_char (di, 'G'))
2002     {
2003       switch (d_next_char (di))
2004         {
2005         case 'V':
2006           return d_make_comp (di, DEMANGLE_COMPONENT_GUARD, d_name (di), NULL);
2007
2008         case 'R':
2009           {
2010             struct demangle_component *name = d_name (di);
2011             return d_make_comp (di, DEMANGLE_COMPONENT_REFTEMP, name,
2012                                 d_number_component (di));
2013           }
2014
2015         case 'A':
2016           return d_make_comp (di, DEMANGLE_COMPONENT_HIDDEN_ALIAS,
2017                               d_encoding (di, 0), NULL);
2018
2019         case 'T':
2020           switch (d_next_char (di))
2021             {
2022             case 'n':
2023               return d_make_comp (di, DEMANGLE_COMPONENT_NONTRANSACTION_CLONE,
2024                                   d_encoding (di, 0), NULL);
2025             default:
2026               /* ??? The proposal is that other letters (such as 'h') stand
2027                  for different variants of transaction cloning, such as
2028                  compiling directly for hardware transaction support.  But
2029                  they still should all be transactional clones of some sort
2030                  so go ahead and call them that.  */
2031             case 't':
2032               return d_make_comp (di, DEMANGLE_COMPONENT_TRANSACTION_CLONE,
2033                                   d_encoding (di, 0), NULL);
2034             }
2035
2036         case 'r':
2037           return d_java_resource (di);
2038
2039         default:
2040           return NULL;
2041         }
2042     }
2043   else
2044     return NULL;
2045 }
2046
2047 /* <call-offset> ::= h <nv-offset> _
2048                  ::= v <v-offset> _
2049
2050    <nv-offset> ::= <(offset) number>
2051
2052    <v-offset> ::= <(offset) number> _ <(virtual offset) number>
2053
2054    The C parameter, if not '\0', is a character we just read which is
2055    the start of the <call-offset>.
2056
2057    We don't display the offset information anywhere.  FIXME: We should
2058    display it in verbose mode.  */
2059
2060 static int
2061 d_call_offset (struct d_info *di, int c)
2062 {
2063   if (c == '\0')
2064     c = d_next_char (di);
2065
2066   if (c == 'h')
2067     d_number (di);
2068   else if (c == 'v')
2069     {
2070       d_number (di);
2071       if (! d_check_char (di, '_'))
2072         return 0;
2073       d_number (di);
2074     }
2075   else
2076     return 0;
2077
2078   if (! d_check_char (di, '_'))
2079     return 0;
2080
2081   return 1;
2082 }
2083
2084 /* <ctor-dtor-name> ::= C1
2085                     ::= C2
2086                     ::= C3
2087                     ::= D0
2088                     ::= D1
2089                     ::= D2
2090 */
2091
2092 static struct demangle_component *
2093 d_ctor_dtor_name (struct d_info *di)
2094 {
2095   if (di->last_name != NULL)
2096     {
2097       if (di->last_name->type == DEMANGLE_COMPONENT_NAME)
2098         di->expansion += di->last_name->u.s_name.len;
2099       else if (di->last_name->type == DEMANGLE_COMPONENT_SUB_STD)
2100         di->expansion += di->last_name->u.s_string.len;
2101     }
2102   switch (d_peek_char (di))
2103     {
2104     case 'C':
2105       {
2106         enum gnu_v3_ctor_kinds kind;
2107
2108         switch (d_peek_next_char (di))
2109           {
2110           case '1':
2111             kind = gnu_v3_complete_object_ctor;
2112             break;
2113           case '2':
2114             kind = gnu_v3_base_object_ctor;
2115             break;
2116           case '3':
2117             kind = gnu_v3_complete_object_allocating_ctor;
2118             break;
2119           case '4':
2120             kind = gnu_v3_unified_ctor;
2121             break;
2122           case '5':
2123             kind = gnu_v3_object_ctor_group;
2124             break;
2125           default:
2126             return NULL;
2127           }
2128         d_advance (di, 2);
2129         return d_make_ctor (di, kind, di->last_name);
2130       }
2131
2132     case 'D':
2133       {
2134         enum gnu_v3_dtor_kinds kind;
2135
2136         switch (d_peek_next_char (di))
2137           {
2138           case '0':
2139             kind = gnu_v3_deleting_dtor;
2140             break;
2141           case '1':
2142             kind = gnu_v3_complete_object_dtor;
2143             break;
2144           case '2':
2145             kind = gnu_v3_base_object_dtor;
2146             break;
2147           /*  digit '3' is not used */
2148           case '4':
2149             kind = gnu_v3_unified_dtor;
2150             break;
2151           case '5':
2152             kind = gnu_v3_object_dtor_group;
2153             break;
2154           default:
2155             return NULL;
2156           }
2157         d_advance (di, 2);
2158         return d_make_dtor (di, kind, di->last_name);
2159       }
2160
2161     default:
2162       return NULL;
2163     }
2164 }
2165
2166 /* <type> ::= <builtin-type>
2167           ::= <function-type>
2168           ::= <class-enum-type>
2169           ::= <array-type>
2170           ::= <pointer-to-member-type>
2171           ::= <template-param>
2172           ::= <template-template-param> <template-args>
2173           ::= <substitution>
2174           ::= <CV-qualifiers> <type>
2175           ::= P <type>
2176           ::= R <type>
2177           ::= O <type> (C++0x)
2178           ::= C <type>
2179           ::= G <type>
2180           ::= U <source-name> <type>
2181
2182    <builtin-type> ::= various one letter codes
2183                   ::= u <source-name>
2184 */
2185
2186 CP_STATIC_IF_GLIBCPP_V3
2187 const struct demangle_builtin_type_info
2188 cplus_demangle_builtin_types[D_BUILTIN_TYPE_COUNT] =
2189 {
2190   /* a */ { NL ("signed char"), NL ("signed char"),     D_PRINT_DEFAULT },
2191   /* b */ { NL ("bool"),        NL ("boolean"),         D_PRINT_BOOL },
2192   /* c */ { NL ("char"),        NL ("byte"),            D_PRINT_DEFAULT },
2193   /* d */ { NL ("double"),      NL ("double"),          D_PRINT_FLOAT },
2194   /* e */ { NL ("long double"), NL ("long double"),     D_PRINT_FLOAT },
2195   /* f */ { NL ("float"),       NL ("float"),           D_PRINT_FLOAT },
2196   /* g */ { NL ("__float128"),  NL ("__float128"),      D_PRINT_FLOAT },
2197   /* h */ { NL ("unsigned char"), NL ("unsigned char"), D_PRINT_DEFAULT },
2198   /* i */ { NL ("int"),         NL ("int"),             D_PRINT_INT },
2199   /* j */ { NL ("unsigned int"), NL ("unsigned"),       D_PRINT_UNSIGNED },
2200   /* k */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
2201   /* l */ { NL ("long"),        NL ("long"),            D_PRINT_LONG },
2202   /* m */ { NL ("unsigned long"), NL ("unsigned long"), D_PRINT_UNSIGNED_LONG },
2203   /* n */ { NL ("__int128"),    NL ("__int128"),        D_PRINT_DEFAULT },
2204   /* o */ { NL ("unsigned __int128"), NL ("unsigned __int128"),
2205             D_PRINT_DEFAULT },
2206   /* p */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
2207   /* q */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
2208   /* r */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
2209   /* s */ { NL ("short"),       NL ("short"),           D_PRINT_DEFAULT },
2210   /* t */ { NL ("unsigned short"), NL ("unsigned short"), D_PRINT_DEFAULT },
2211   /* u */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
2212   /* v */ { NL ("void"),        NL ("void"),            D_PRINT_VOID },
2213   /* w */ { NL ("wchar_t"),     NL ("char"),            D_PRINT_DEFAULT },
2214   /* x */ { NL ("long long"),   NL ("long"),            D_PRINT_LONG_LONG },
2215   /* y */ { NL ("unsigned long long"), NL ("unsigned long long"),
2216             D_PRINT_UNSIGNED_LONG_LONG },
2217   /* z */ { NL ("..."),         NL ("..."),             D_PRINT_DEFAULT },
2218   /* 26 */ { NL ("decimal32"),  NL ("decimal32"),       D_PRINT_DEFAULT },
2219   /* 27 */ { NL ("decimal64"),  NL ("decimal64"),       D_PRINT_DEFAULT },
2220   /* 28 */ { NL ("decimal128"), NL ("decimal128"),      D_PRINT_DEFAULT },
2221   /* 29 */ { NL ("half"),       NL ("half"),            D_PRINT_FLOAT },
2222   /* 30 */ { NL ("char16_t"),   NL ("char16_t"),        D_PRINT_DEFAULT },
2223   /* 31 */ { NL ("char32_t"),   NL ("char32_t"),        D_PRINT_DEFAULT },
2224   /* 32 */ { NL ("decltype(nullptr)"),  NL ("decltype(nullptr)"),
2225              D_PRINT_DEFAULT },
2226 };
2227
2228 CP_STATIC_IF_GLIBCPP_V3
2229 struct demangle_component *
2230 cplus_demangle_type (struct d_info *di)
2231 {
2232   char peek;
2233   struct demangle_component *ret;
2234   int can_subst;
2235
2236   /* The ABI specifies that when CV-qualifiers are used, the base type
2237      is substitutable, and the fully qualified type is substitutable,
2238      but the base type with a strict subset of the CV-qualifiers is
2239      not substitutable.  The natural recursive implementation of the
2240      CV-qualifiers would cause subsets to be substitutable, so instead
2241      we pull them all off now.
2242
2243      FIXME: The ABI says that order-insensitive vendor qualifiers
2244      should be handled in the same way, but we have no way to tell
2245      which vendor qualifiers are order-insensitive and which are
2246      order-sensitive.  So we just assume that they are all
2247      order-sensitive.  g++ 3.4 supports only one vendor qualifier,
2248      __vector, and it treats it as order-sensitive when mangling
2249      names.  */
2250
2251   peek = d_peek_char (di);
2252   if (peek == 'r' || peek == 'V' || peek == 'K')
2253     {
2254       struct demangle_component **pret;
2255
2256       pret = d_cv_qualifiers (di, &ret, 0);
2257       if (pret == NULL)
2258         return NULL;
2259       if (d_peek_char (di) == 'F')
2260         {
2261           /* cv-qualifiers before a function type apply to 'this',
2262              so avoid adding the unqualified function type to
2263              the substitution list.  */
2264           *pret = d_function_type (di);
2265         }
2266       else
2267         *pret = cplus_demangle_type (di);
2268       if (!*pret)
2269         return NULL;
2270       if ((*pret)->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS
2271           || (*pret)->type == DEMANGLE_COMPONENT_REFERENCE_THIS)
2272         {
2273           /* Move the ref-qualifier outside the cv-qualifiers so that
2274              they are printed in the right order.  */
2275           struct demangle_component *fn = d_left (*pret);
2276           d_left (*pret) = ret;
2277           ret = *pret;
2278           *pret = fn;
2279         }
2280       if (! d_add_substitution (di, ret))
2281         return NULL;
2282       return ret;
2283     }
2284
2285   can_subst = 1;
2286
2287   switch (peek)
2288     {
2289     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2290     case 'h': case 'i': case 'j':           case 'l': case 'm': case 'n':
2291     case 'o':                               case 's': case 't':
2292     case 'v': case 'w': case 'x': case 'y': case 'z':
2293       ret = d_make_builtin_type (di,
2294                                  &cplus_demangle_builtin_types[peek - 'a']);
2295       di->expansion += ret->u.s_builtin.type->len;
2296       can_subst = 0;
2297       d_advance (di, 1);
2298       break;
2299
2300     case 'u':
2301       d_advance (di, 1);
2302       ret = d_make_comp (di, DEMANGLE_COMPONENT_VENDOR_TYPE,
2303                          d_source_name (di), NULL);
2304       break;
2305
2306     case 'F':
2307       ret = d_function_type (di);
2308       break;
2309
2310     case '0': case '1': case '2': case '3': case '4':
2311     case '5': case '6': case '7': case '8': case '9':
2312     case 'N':
2313     case 'Z':
2314       ret = d_class_enum_type (di);
2315       break;
2316
2317     case 'A':
2318       ret = d_array_type (di);
2319       break;
2320
2321     case 'M':
2322       ret = d_pointer_to_member_type (di);
2323       break;
2324
2325     case 'T':
2326       ret = d_template_param (di);
2327       if (d_peek_char (di) == 'I')
2328         {
2329           /* This may be <template-template-param> <template-args>.
2330              If this is the type for a conversion operator, we can
2331              have a <template-template-param> here only by following
2332              a derivation like this:
2333
2334              <nested-name>
2335              -> <template-prefix> <template-args>
2336              -> <prefix> <template-unqualified-name> <template-args>
2337              -> <unqualified-name> <template-unqualified-name> <template-args>
2338              -> <source-name> <template-unqualified-name> <template-args>
2339              -> <source-name> <operator-name> <template-args>
2340              -> <source-name> cv <type> <template-args>
2341              -> <source-name> cv <template-template-param> <template-args> <template-args>
2342
2343              where the <template-args> is followed by another.
2344              Otherwise, we must have a derivation like this:
2345
2346              <nested-name>
2347              -> <template-prefix> <template-args>
2348              -> <prefix> <template-unqualified-name> <template-args>
2349              -> <unqualified-name> <template-unqualified-name> <template-args>
2350              -> <source-name> <template-unqualified-name> <template-args>
2351              -> <source-name> <operator-name> <template-args>
2352              -> <source-name> cv <type> <template-args>
2353              -> <source-name> cv <template-param> <template-args>
2354
2355              where we need to leave the <template-args> to be processed
2356              by d_prefix (following the <template-prefix>).
2357
2358              The <template-template-param> part is a substitution
2359              candidate.  */
2360           if (! di->is_conversion)
2361             {
2362               if (! d_add_substitution (di, ret))
2363                 return NULL;
2364               ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2365                                  d_template_args (di));
2366             }
2367           else
2368             {
2369               struct demangle_component *args;
2370               struct d_info_checkpoint checkpoint;
2371
2372               d_checkpoint (di, &checkpoint);
2373               args = d_template_args (di);
2374               if (d_peek_char (di) == 'I')
2375                 {
2376                   if (! d_add_substitution (di, ret))
2377                     return NULL;
2378                   ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2379                                      args);
2380                 }
2381               else
2382                 d_backtrack (di, &checkpoint);
2383             }
2384         }
2385       break;
2386
2387     case 'S':
2388       /* If this is a special substitution, then it is the start of
2389          <class-enum-type>.  */
2390       {
2391         char peek_next;
2392
2393         peek_next = d_peek_next_char (di);
2394         if (IS_DIGIT (peek_next)
2395             || peek_next == '_'
2396             || IS_UPPER (peek_next))
2397           {
2398             ret = d_substitution (di, 0);
2399             /* The substituted name may have been a template name and
2400                may be followed by tepmlate args.  */
2401             if (d_peek_char (di) == 'I')
2402               ret = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, ret,
2403                                  d_template_args (di));
2404             else
2405               can_subst = 0;
2406           }
2407         else
2408           {
2409             ret = d_class_enum_type (di);
2410             /* If the substitution was a complete type, then it is not
2411                a new substitution candidate.  However, if the
2412                substitution was followed by template arguments, then
2413                the whole thing is a substitution candidate.  */
2414             if (ret != NULL && ret->type == DEMANGLE_COMPONENT_SUB_STD)
2415               can_subst = 0;
2416           }
2417       }
2418       break;
2419
2420     case 'O':
2421       d_advance (di, 1);
2422       ret = d_make_comp (di, DEMANGLE_COMPONENT_RVALUE_REFERENCE,
2423                          cplus_demangle_type (di), NULL);
2424       break;
2425
2426     case 'P':
2427       d_advance (di, 1);
2428       ret = d_make_comp (di, DEMANGLE_COMPONENT_POINTER,
2429                          cplus_demangle_type (di), NULL);
2430       break;
2431
2432     case 'R':
2433       d_advance (di, 1);
2434       ret = d_make_comp (di, DEMANGLE_COMPONENT_REFERENCE,
2435                          cplus_demangle_type (di), NULL);
2436       break;
2437
2438     case 'C':
2439       d_advance (di, 1);
2440       ret = d_make_comp (di, DEMANGLE_COMPONENT_COMPLEX,
2441                          cplus_demangle_type (di), NULL);
2442       break;
2443
2444     case 'G':
2445       d_advance (di, 1);
2446       ret = d_make_comp (di, DEMANGLE_COMPONENT_IMAGINARY,
2447                          cplus_demangle_type (di), NULL);
2448       break;
2449
2450     case 'U':
2451       d_advance (di, 1);
2452       ret = d_source_name (di);
2453       ret = d_make_comp (di, DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL,
2454                          cplus_demangle_type (di), ret);
2455       break;
2456
2457     case 'D':
2458       can_subst = 0;
2459       d_advance (di, 1);
2460       peek = d_next_char (di);
2461       switch (peek)
2462         {
2463         case 'T':
2464         case 't':
2465           /* decltype (expression) */
2466           ret = d_make_comp (di, DEMANGLE_COMPONENT_DECLTYPE,
2467                              d_expression (di), NULL);
2468           if (ret && d_next_char (di) != 'E')
2469             ret = NULL;
2470           can_subst = 1;
2471           break;
2472           
2473         case 'p':
2474           /* Pack expansion.  */
2475           ret = d_make_comp (di, DEMANGLE_COMPONENT_PACK_EXPANSION,
2476                              cplus_demangle_type (di), NULL);
2477           can_subst = 1;
2478           break;
2479
2480         case 'a':
2481           /* auto */
2482           ret = d_make_name (di, "auto", 4);
2483           break;
2484           
2485         case 'f':
2486           /* 32-bit decimal floating point */
2487           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[26]);
2488           di->expansion += ret->u.s_builtin.type->len;
2489           break;
2490         case 'd':
2491           /* 64-bit DFP */
2492           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[27]);
2493           di->expansion += ret->u.s_builtin.type->len;
2494           break;
2495         case 'e':
2496           /* 128-bit DFP */
2497           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[28]);
2498           di->expansion += ret->u.s_builtin.type->len;
2499           break;
2500         case 'h':
2501           /* 16-bit half-precision FP */
2502           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[29]);
2503           di->expansion += ret->u.s_builtin.type->len;
2504           break;
2505         case 's':
2506           /* char16_t */
2507           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[30]);
2508           di->expansion += ret->u.s_builtin.type->len;
2509           break;
2510         case 'i':
2511           /* char32_t */
2512           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[31]);
2513           di->expansion += ret->u.s_builtin.type->len;
2514           break;
2515
2516         case 'F':
2517           /* Fixed point types. DF<int bits><length><fract bits><sat>  */
2518           ret = d_make_empty (di);
2519           ret->type = DEMANGLE_COMPONENT_FIXED_TYPE;
2520           if ((ret->u.s_fixed.accum = IS_DIGIT (d_peek_char (di))))
2521             /* For demangling we don't care about the bits.  */
2522             d_number (di);
2523           ret->u.s_fixed.length = cplus_demangle_type (di);
2524           if (ret->u.s_fixed.length == NULL)
2525             return NULL;
2526           d_number (di);
2527           peek = d_next_char (di);
2528           ret->u.s_fixed.sat = (peek == 's');
2529           break;
2530
2531         case 'v':
2532           ret = d_vector_type (di);
2533           can_subst = 1;
2534           break;
2535
2536         case 'n':
2537           /* decltype(nullptr) */
2538           ret = d_make_builtin_type (di, &cplus_demangle_builtin_types[32]);
2539           di->expansion += ret->u.s_builtin.type->len;
2540           break;
2541
2542         default:
2543           return NULL;
2544         }
2545       break;
2546
2547     default:
2548       return NULL;
2549     }
2550
2551   if (can_subst)
2552     {
2553       if (! d_add_substitution (di, ret))
2554         return NULL;
2555     }
2556
2557   return ret;
2558 }
2559
2560 /* <CV-qualifiers> ::= [r] [V] [K]  */
2561
2562 static struct demangle_component **
2563 d_cv_qualifiers (struct d_info *di,
2564                  struct demangle_component **pret, int member_fn)
2565 {
2566   struct demangle_component **pstart;
2567   char peek;
2568
2569   pstart = pret;
2570   peek = d_peek_char (di);
2571   while (peek == 'r' || peek == 'V' || peek == 'K')
2572     {
2573       enum demangle_component_type t;
2574
2575       d_advance (di, 1);
2576       if (peek == 'r')
2577         {
2578           t = (member_fn
2579                ? DEMANGLE_COMPONENT_RESTRICT_THIS
2580                : DEMANGLE_COMPONENT_RESTRICT);
2581           di->expansion += sizeof "restrict";
2582         }
2583       else if (peek == 'V')
2584         {
2585           t = (member_fn
2586                ? DEMANGLE_COMPONENT_VOLATILE_THIS
2587                : DEMANGLE_COMPONENT_VOLATILE);
2588           di->expansion += sizeof "volatile";
2589         }
2590       else
2591         {
2592           t = (member_fn
2593                ? DEMANGLE_COMPONENT_CONST_THIS
2594                : DEMANGLE_COMPONENT_CONST);
2595           di->expansion += sizeof "const";
2596         }
2597
2598       *pret = d_make_comp (di, t, NULL, NULL);
2599       if (*pret == NULL)
2600         return NULL;
2601       pret = &d_left (*pret);
2602
2603       peek = d_peek_char (di);
2604     }
2605
2606   if (!member_fn && peek == 'F')
2607     {
2608       while (pstart != pret)
2609         {
2610           switch ((*pstart)->type)
2611             {
2612             case DEMANGLE_COMPONENT_RESTRICT:
2613               (*pstart)->type = DEMANGLE_COMPONENT_RESTRICT_THIS;
2614               break;
2615             case DEMANGLE_COMPONENT_VOLATILE:
2616               (*pstart)->type = DEMANGLE_COMPONENT_VOLATILE_THIS;
2617               break;
2618             case DEMANGLE_COMPONENT_CONST:
2619               (*pstart)->type = DEMANGLE_COMPONENT_CONST_THIS;
2620               break;
2621             default:
2622               break;
2623             }
2624           pstart = &d_left (*pstart);
2625         }
2626     }
2627
2628   return pret;
2629 }
2630
2631 /* <ref-qualifier> ::= R
2632                    ::= O */
2633
2634 static struct demangle_component *
2635 d_ref_qualifier (struct d_info *di, struct demangle_component *sub)
2636 {
2637   struct demangle_component *ret = sub;
2638   char peek;
2639
2640   peek = d_peek_char (di);
2641   if (peek == 'R' || peek == 'O')
2642     {
2643       enum demangle_component_type t;
2644       if (peek == 'R')
2645         {
2646           t = DEMANGLE_COMPONENT_REFERENCE_THIS;
2647           di->expansion += sizeof "&";
2648         }
2649       else
2650         {
2651           t = DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS;
2652           di->expansion += sizeof "&&";
2653         }
2654       d_advance (di, 1);
2655
2656       ret = d_make_comp (di, t, ret, NULL);
2657     }
2658
2659   return ret;
2660 }
2661
2662 /* <function-type> ::= F [Y] <bare-function-type> [<ref-qualifier>] E  */
2663
2664 static struct demangle_component *
2665 d_function_type (struct d_info *di)
2666 {
2667   struct demangle_component *ret;
2668
2669   if (! d_check_char (di, 'F'))
2670     return NULL;
2671   if (d_peek_char (di) == 'Y')
2672     {
2673       /* Function has C linkage.  We don't print this information.
2674          FIXME: We should print it in verbose mode.  */
2675       d_advance (di, 1);
2676     }
2677   ret = d_bare_function_type (di, 1);
2678   ret = d_ref_qualifier (di, ret);
2679
2680   if (! d_check_char (di, 'E'))
2681     return NULL;
2682   return ret;
2683 }
2684
2685 /* <type>+ */
2686
2687 static struct demangle_component *
2688 d_parmlist (struct d_info *di)
2689 {
2690   struct demangle_component *tl;
2691   struct demangle_component **ptl;
2692
2693   tl = NULL;
2694   ptl = &tl;
2695   while (1)
2696     {
2697       struct demangle_component *type;
2698
2699       char peek = d_peek_char (di);
2700       if (peek == '\0' || peek == 'E' || peek == '.')
2701         break;
2702       if ((peek == 'R' || peek == 'O')
2703           && d_peek_next_char (di) == 'E')
2704         /* Function ref-qualifier, not a ref prefix for a parameter type.  */
2705         break;
2706       type = cplus_demangle_type (di);
2707       if (type == NULL)
2708         return NULL;
2709       *ptl = d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, type, NULL);
2710       if (*ptl == NULL)
2711         return NULL;
2712       ptl = &d_right (*ptl);
2713     }
2714
2715   /* There should be at least one parameter type besides the optional
2716      return type.  A function which takes no arguments will have a
2717      single parameter type void.  */
2718   if (tl == NULL)
2719     return NULL;
2720
2721   /* If we have a single parameter type void, omit it.  */
2722   if (d_right (tl) == NULL
2723       && d_left (tl)->type == DEMANGLE_COMPONENT_BUILTIN_TYPE
2724       && d_left (tl)->u.s_builtin.type->print == D_PRINT_VOID)
2725     {
2726       di->expansion -= d_left (tl)->u.s_builtin.type->len;
2727       d_left (tl) = NULL;
2728     }
2729
2730   return tl;
2731 }
2732
2733 /* <bare-function-type> ::= [J]<type>+  */
2734
2735 static struct demangle_component *
2736 d_bare_function_type (struct d_info *di, int has_return_type)
2737 {
2738   struct demangle_component *return_type;
2739   struct demangle_component *tl;
2740   char peek;
2741
2742   /* Detect special qualifier indicating that the first argument
2743      is the return type.  */
2744   peek = d_peek_char (di);
2745   if (peek == 'J')
2746     {
2747       d_advance (di, 1);
2748       has_return_type = 1;
2749     }
2750
2751   if (has_return_type)
2752     {
2753       return_type = cplus_demangle_type (di);
2754       if (return_type == NULL)
2755         return NULL;
2756     }
2757   else
2758     return_type = NULL;
2759
2760   tl = d_parmlist (di);
2761   if (tl == NULL)
2762     return NULL;
2763
2764   return d_make_comp (di, DEMANGLE_COMPONENT_FUNCTION_TYPE,
2765                       return_type, tl);
2766 }
2767
2768 /* <class-enum-type> ::= <name>  */
2769
2770 static struct demangle_component *
2771 d_class_enum_type (struct d_info *di)
2772 {
2773   return d_name (di);
2774 }
2775
2776 /* <array-type> ::= A <(positive dimension) number> _ <(element) type>
2777                 ::= A [<(dimension) expression>] _ <(element) type>
2778 */
2779
2780 static struct demangle_component *
2781 d_array_type (struct d_info *di)
2782 {
2783   char peek;
2784   struct demangle_component *dim;
2785
2786   if (! d_check_char (di, 'A'))
2787     return NULL;
2788
2789   peek = d_peek_char (di);
2790   if (peek == '_')
2791     dim = NULL;
2792   else if (IS_DIGIT (peek))
2793     {
2794       const char *s;
2795
2796       s = d_str (di);
2797       do
2798         {
2799           d_advance (di, 1);
2800           peek = d_peek_char (di);
2801         }
2802       while (IS_DIGIT (peek));
2803       dim = d_make_name (di, s, d_str (di) - s);
2804       if (dim == NULL)
2805         return NULL;
2806     }
2807   else
2808     {
2809       dim = d_expression (di);
2810       if (dim == NULL)
2811         return NULL;
2812     }
2813
2814   if (! d_check_char (di, '_'))
2815     return NULL;
2816
2817   return d_make_comp (di, DEMANGLE_COMPONENT_ARRAY_TYPE, dim,
2818                       cplus_demangle_type (di));
2819 }
2820
2821 /* <vector-type> ::= Dv <number> _ <type>
2822                  ::= Dv _ <expression> _ <type> */
2823
2824 static struct demangle_component *
2825 d_vector_type (struct d_info *di)
2826 {
2827   char peek;
2828   struct demangle_component *dim;
2829
2830   peek = d_peek_char (di);
2831   if (peek == '_')
2832     {
2833       d_advance (di, 1);
2834       dim = d_expression (di);
2835     }
2836   else
2837     dim = d_number_component (di);
2838
2839   if (dim == NULL)
2840     return NULL;
2841
2842   if (! d_check_char (di, '_'))
2843     return NULL;
2844
2845   return d_make_comp (di, DEMANGLE_COMPONENT_VECTOR_TYPE, dim,
2846                       cplus_demangle_type (di));
2847 }
2848
2849 /* <pointer-to-member-type> ::= M <(class) type> <(member) type>  */
2850
2851 static struct demangle_component *
2852 d_pointer_to_member_type (struct d_info *di)
2853 {
2854   struct demangle_component *cl;
2855   struct demangle_component *mem;
2856
2857   if (! d_check_char (di, 'M'))
2858     return NULL;
2859
2860   cl = cplus_demangle_type (di);
2861   if (cl == NULL)
2862     return NULL;
2863
2864   /* The ABI says, "The type of a non-static member function is considered
2865      to be different, for the purposes of substitution, from the type of a
2866      namespace-scope or static member function whose type appears
2867      similar. The types of two non-static member functions are considered
2868      to be different, for the purposes of substitution, if the functions
2869      are members of different classes. In other words, for the purposes of
2870      substitution, the class of which the function is a member is
2871      considered part of the type of function."
2872
2873      For a pointer to member function, this call to cplus_demangle_type
2874      will end up adding a (possibly qualified) non-member function type to
2875      the substitution table, which is not correct; however, the member
2876      function type will never be used in a substitution, so putting the
2877      wrong type in the substitution table is harmless.  */
2878
2879   mem = cplus_demangle_type (di);
2880   if (mem == NULL)
2881     return NULL;
2882
2883   return d_make_comp (di, DEMANGLE_COMPONENT_PTRMEM_TYPE, cl, mem);
2884 }
2885
2886 /* <non-negative number> _ */
2887
2888 static long
2889 d_compact_number (struct d_info *di)
2890 {
2891   long num;
2892   if (d_peek_char (di) == '_')
2893     num = 0;
2894   else if (d_peek_char (di) == 'n')
2895     return -1;
2896   else
2897     num = d_number (di) + 1;
2898
2899   if (! d_check_char (di, '_'))
2900     return -1;
2901   return num;
2902 }
2903
2904 /* <template-param> ::= T_
2905                     ::= T <(parameter-2 non-negative) number> _
2906 */
2907
2908 static struct demangle_component *
2909 d_template_param (struct d_info *di)
2910 {
2911   long param;
2912
2913   if (! d_check_char (di, 'T'))
2914     return NULL;
2915
2916   param = d_compact_number (di);
2917   if (param < 0)
2918     return NULL;
2919
2920   ++di->did_subs;
2921
2922   return d_make_template_param (di, param);
2923 }
2924
2925 /* <template-args> ::= I <template-arg>+ E  */
2926
2927 static struct demangle_component *
2928 d_template_args (struct d_info *di)
2929 {
2930   struct demangle_component *hold_last_name;
2931   struct demangle_component *al;
2932   struct demangle_component **pal;
2933
2934   /* Preserve the last name we saw--don't let the template arguments
2935      clobber it, as that would give us the wrong name for a subsequent
2936      constructor or destructor.  */
2937   hold_last_name = di->last_name;
2938
2939   if (d_peek_char (di) != 'I'
2940       && d_peek_char (di) != 'J')
2941     return NULL;
2942   d_advance (di, 1);
2943
2944   if (d_peek_char (di) == 'E')
2945     {
2946       /* An argument pack can be empty.  */
2947       d_advance (di, 1);
2948       return d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE_ARGLIST, NULL, NULL);
2949     }
2950
2951   al = NULL;
2952   pal = &al;
2953   while (1)
2954     {
2955       struct demangle_component *a;
2956
2957       a = d_template_arg (di);
2958       if (a == NULL)
2959         return NULL;
2960
2961       *pal = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE_ARGLIST, a, NULL);
2962       if (*pal == NULL)
2963         return NULL;
2964       pal = &d_right (*pal);
2965
2966       if (d_peek_char (di) == 'E')
2967         {
2968           d_advance (di, 1);
2969           break;
2970         }
2971     }
2972
2973   di->last_name = hold_last_name;
2974
2975   return al;
2976 }
2977
2978 /* <template-arg> ::= <type>
2979                   ::= X <expression> E
2980                   ::= <expr-primary>
2981 */
2982
2983 static struct demangle_component *
2984 d_template_arg (struct d_info *di)
2985 {
2986   struct demangle_component *ret;
2987
2988   switch (d_peek_char (di))
2989     {
2990     case 'X':
2991       d_advance (di, 1);
2992       ret = d_expression (di);
2993       if (! d_check_char (di, 'E'))
2994         return NULL;
2995       return ret;
2996
2997     case 'L':
2998       return d_expr_primary (di);
2999
3000     case 'I':
3001     case 'J':
3002       /* An argument pack.  */
3003       return d_template_args (di);
3004
3005     default:
3006       return cplus_demangle_type (di);
3007     }
3008 }
3009
3010 /* Parse a sequence of expressions until we hit the terminator
3011    character.  */
3012
3013 static struct demangle_component *
3014 d_exprlist (struct d_info *di, char terminator)
3015 {
3016   struct demangle_component *list = NULL;
3017   struct demangle_component **p = &list;
3018
3019   if (d_peek_char (di) == terminator)
3020     {
3021       d_advance (di, 1);
3022       return d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, NULL, NULL);
3023     }
3024
3025   while (1)
3026     {
3027       struct demangle_component *arg = d_expression (di);
3028       if (arg == NULL)
3029         return NULL;
3030
3031       *p = d_make_comp (di, DEMANGLE_COMPONENT_ARGLIST, arg, NULL);
3032       if (*p == NULL)
3033         return NULL;
3034       p = &d_right (*p);
3035
3036       if (d_peek_char (di) == terminator)
3037         {
3038           d_advance (di, 1);
3039           break;
3040         }
3041     }
3042
3043   return list;
3044 }
3045
3046 /* Returns nonzero iff OP is an operator for a C++ cast: const_cast,
3047    dynamic_cast, static_cast or reinterpret_cast.  */
3048
3049 static int
3050 op_is_new_cast (struct demangle_component *op)
3051 {
3052   const char *code = op->u.s_operator.op->code;
3053   return (code[1] == 'c'
3054           && (code[0] == 's' || code[0] == 'd'
3055               || code[0] == 'c' || code[0] == 'r'));
3056 }
3057
3058 /* <expression> ::= <(unary) operator-name> <expression>
3059                 ::= <(binary) operator-name> <expression> <expression>
3060                 ::= <(trinary) operator-name> <expression> <expression> <expression>
3061                 ::= cl <expression>+ E
3062                 ::= st <type>
3063                 ::= <template-param>
3064                 ::= sr <type> <unqualified-name>
3065                 ::= sr <type> <unqualified-name> <template-args>
3066                 ::= <expr-primary>
3067 */
3068
3069 static inline struct demangle_component *
3070 d_expression_1 (struct d_info *di)
3071 {
3072   char peek;
3073
3074   peek = d_peek_char (di);
3075   if (peek == 'L')
3076     return d_expr_primary (di);
3077   else if (peek == 'T')
3078     return d_template_param (di);
3079   else if (peek == 's' && d_peek_next_char (di) == 'r')
3080     {
3081       struct demangle_component *type;
3082       struct demangle_component *name;
3083
3084       d_advance (di, 2);
3085       type = cplus_demangle_type (di);
3086       name = d_unqualified_name (di);
3087       if (d_peek_char (di) != 'I')
3088         return d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME, type, name);
3089       else
3090         return d_make_comp (di, DEMANGLE_COMPONENT_QUAL_NAME, type,
3091                             d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, name,
3092                                          d_template_args (di)));
3093     }
3094   else if (peek == 's' && d_peek_next_char (di) == 'p')
3095     {
3096       d_advance (di, 2);
3097       return d_make_comp (di, DEMANGLE_COMPONENT_PACK_EXPANSION,
3098                           d_expression_1 (di), NULL);
3099     }
3100   else if (peek == 'f' && d_peek_next_char (di) == 'p')
3101     {
3102       /* Function parameter used in a late-specified return type.  */
3103       int index;
3104       d_advance (di, 2);
3105       if (d_peek_char (di) == 'T')
3106         {
3107           /* 'this' parameter.  */
3108           d_advance (di, 1);
3109           index = 0;
3110         }
3111       else
3112         {
3113           index = d_compact_number (di) + 1;
3114           if (index == 0)
3115             return NULL;
3116         }
3117       return d_make_function_param (di, index);
3118     }
3119   else if (IS_DIGIT (peek)
3120            || (peek == 'o' && d_peek_next_char (di) == 'n'))
3121     {
3122       /* We can get an unqualified name as an expression in the case of
3123          a dependent function call, i.e. decltype(f(t)).  */
3124       struct demangle_component *name;
3125
3126       if (peek == 'o')
3127         /* operator-function-id, i.e. operator+(t).  */
3128         d_advance (di, 2);
3129
3130       name = d_unqualified_name (di);
3131       if (name == NULL)
3132         return NULL;
3133       if (d_peek_char (di) == 'I')
3134         return d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE, name,
3135                             d_template_args (di));
3136       else
3137         return name;
3138     }
3139   else if ((peek == 'i' || peek == 't')
3140            && d_peek_next_char (di) == 'l')
3141     {
3142       /* Brace-enclosed initializer list, untyped or typed.  */
3143       struct demangle_component *type = NULL;
3144       if (peek == 't')
3145         type = cplus_demangle_type (di);
3146       d_advance (di, 2);
3147       return d_make_comp (di, DEMANGLE_COMPONENT_INITIALIZER_LIST,
3148                           type, d_exprlist (di, 'E'));
3149     }
3150   else
3151     {
3152       struct demangle_component *op;
3153       const char *code = NULL;
3154       int args;
3155
3156       op = d_operator_name (di);
3157       if (op == NULL)
3158         return NULL;
3159
3160       if (op->type == DEMANGLE_COMPONENT_OPERATOR)
3161         {
3162           code = op->u.s_operator.op->code;
3163           di->expansion += op->u.s_operator.op->len - 2;
3164           if (strcmp (code, "st") == 0)
3165             return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
3166                                 cplus_demangle_type (di));
3167         }
3168
3169       switch (op->type)
3170         {
3171         default:
3172           return NULL;
3173         case DEMANGLE_COMPONENT_OPERATOR:
3174           args = op->u.s_operator.op->args;
3175           break;
3176         case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
3177           args = op->u.s_extended_operator.args;
3178           break;
3179         case DEMANGLE_COMPONENT_CAST:
3180           args = 1;
3181           break;
3182         }
3183
3184       switch (args)
3185         {
3186         case 0:
3187           return d_make_comp (di, DEMANGLE_COMPONENT_NULLARY, op, NULL);
3188
3189         case 1:
3190           {
3191             struct demangle_component *operand;
3192             int suffix = 0;
3193
3194             if (code && (code[0] == 'p' || code[0] == 'm')
3195                 && code[1] == code[0])
3196               /* pp_ and mm_ are the prefix variants.  */
3197               suffix = !d_check_char (di, '_');
3198
3199             if (op->type == DEMANGLE_COMPONENT_CAST
3200                 && d_check_char (di, '_'))
3201               operand = d_exprlist (di, 'E');
3202             else
3203               operand = d_expression_1 (di);
3204
3205             if (suffix)
3206               /* Indicate the suffix variant for d_print_comp.  */
3207               return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
3208                                   d_make_comp (di,
3209                                                DEMANGLE_COMPONENT_BINARY_ARGS,
3210                                                operand, operand));
3211             else
3212               return d_make_comp (di, DEMANGLE_COMPONENT_UNARY, op,
3213                                   operand);
3214           }
3215         case 2:
3216           {
3217             struct demangle_component *left;
3218             struct demangle_component *right;
3219
3220             if (op_is_new_cast (op))
3221               left = cplus_demangle_type (di);
3222             else
3223               left = d_expression_1 (di);
3224             if (!strcmp (code, "cl"))
3225               right = d_exprlist (di, 'E');
3226             else if (!strcmp (code, "dt") || !strcmp (code, "pt"))
3227               {
3228                 right = d_unqualified_name (di);
3229                 if (d_peek_char (di) == 'I')
3230                   right = d_make_comp (di, DEMANGLE_COMPONENT_TEMPLATE,
3231                                        right, d_template_args (di));
3232               }
3233             else
3234               right = d_expression_1 (di);
3235
3236             return d_make_comp (di, DEMANGLE_COMPONENT_BINARY, op,
3237                                 d_make_comp (di,
3238                                              DEMANGLE_COMPONENT_BINARY_ARGS,
3239                                              left, right));
3240           }
3241         case 3:
3242           {
3243             struct demangle_component *first;
3244             struct demangle_component *second;
3245             struct demangle_component *third;
3246
3247             if (!strcmp (code, "qu"))
3248               {
3249                 /* ?: expression.  */
3250                 first = d_expression_1 (di);
3251                 second = d_expression_1 (di);
3252                 third = d_expression_1 (di);
3253               }
3254             else if (code[0] == 'n')
3255               {
3256                 /* new-expression.  */
3257                 if (code[1] != 'w' && code[1] != 'a')
3258                   return NULL;
3259                 first = d_exprlist (di, '_');
3260                 second = cplus_demangle_type (di);
3261                 if (d_peek_char (di) == 'E')
3262                   {
3263                     d_advance (di, 1);
3264                     third = NULL;
3265                   }
3266                 else if (d_peek_char (di) == 'p'
3267                          && d_peek_next_char (di) == 'i')
3268                   {
3269                     /* Parenthesized initializer.  */
3270                     d_advance (di, 2);
3271                     third = d_exprlist (di, 'E');
3272                   }
3273                 else if (d_peek_char (di) == 'i'
3274                          && d_peek_next_char (di) == 'l')
3275                   /* initializer-list.  */
3276                   third = d_expression_1 (di);
3277                 else
3278                   return NULL;
3279               }
3280             else
3281               return NULL;
3282             return d_make_comp (di, DEMANGLE_COMPONENT_TRINARY, op,
3283                                 d_make_comp (di,
3284                                              DEMANGLE_COMPONENT_TRINARY_ARG1,
3285                                              first,
3286                                              d_make_comp (di,
3287                                                           DEMANGLE_COMPONENT_TRINARY_ARG2,
3288                                                           second, third)));
3289           }
3290         default:
3291           return NULL;
3292         }
3293     }
3294 }
3295
3296 static struct demangle_component *
3297 d_expression (struct d_info *di)
3298 {
3299   struct demangle_component *ret;
3300   int was_expression = di->is_expression;
3301
3302   di->is_expression = 1;
3303   ret = d_expression_1 (di);
3304   di->is_expression = was_expression;
3305   return ret;
3306 }
3307
3308 /* <expr-primary> ::= L <type> <(value) number> E
3309                   ::= L <type> <(value) float> E
3310                   ::= L <mangled-name> E
3311 */
3312
3313 static struct demangle_component *
3314 d_expr_primary (struct d_info *di)
3315 {
3316   struct demangle_component *ret;
3317
3318   if (! d_check_char (di, 'L'))
3319     return NULL;
3320   if (d_peek_char (di) == '_'
3321       /* Workaround for G++ bug; see comment in write_template_arg.  */
3322       || d_peek_char (di) == 'Z')
3323     ret = cplus_demangle_mangled_name (di, 0);
3324   else
3325     {
3326       struct demangle_component *type;
3327       enum demangle_component_type t;
3328       const char *s;
3329
3330       type = cplus_demangle_type (di);
3331       if (type == NULL)
3332         return NULL;
3333
3334       /* If we have a type we know how to print, we aren't going to
3335          print the type name itself.  */
3336       if (type->type == DEMANGLE_COMPONENT_BUILTIN_TYPE
3337           && type->u.s_builtin.type->print != D_PRINT_DEFAULT)
3338         di->expansion -= type->u.s_builtin.type->len;
3339
3340       /* Rather than try to interpret the literal value, we just
3341          collect it as a string.  Note that it's possible to have a
3342          floating point literal here.  The ABI specifies that the
3343          format of such literals is machine independent.  That's fine,
3344          but what's not fine is that versions of g++ up to 3.2 with
3345          -fabi-version=1 used upper case letters in the hex constant,
3346          and dumped out gcc's internal representation.  That makes it
3347          hard to tell where the constant ends, and hard to dump the
3348          constant in any readable form anyhow.  We don't attempt to
3349          handle these cases.  */
3350
3351       t = DEMANGLE_COMPONENT_LITERAL;
3352       if (d_peek_char (di) == 'n')
3353         {
3354           t = DEMANGLE_COMPONENT_LITERAL_NEG;
3355           d_advance (di, 1);
3356         }
3357       s = d_str (di);
3358       while (d_peek_char (di) != 'E')
3359         {
3360           if (d_peek_char (di) == '\0')
3361             return NULL;
3362           d_advance (di, 1);
3363         }
3364       ret = d_make_comp (di, t, type, d_make_name (di, s, d_str (di) - s));
3365     }
3366   if (! d_check_char (di, 'E'))
3367     return NULL;
3368   return ret;
3369 }
3370
3371 /* <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
3372                 ::= Z <(function) encoding> E s [<discriminator>]
3373                 ::= Z <(function) encoding> E d [<parameter> number>] _ <entity name>
3374 */
3375
3376 static struct demangle_component *
3377 d_local_name (struct d_info *di)
3378 {
3379   struct demangle_component *function;
3380
3381   if (! d_check_char (di, 'Z'))
3382     return NULL;
3383
3384   function = d_encoding (di, 0);
3385
3386   if (! d_check_char (di, 'E'))
3387     return NULL;
3388
3389   if (d_peek_char (di) == 's')
3390     {
3391       d_advance (di, 1);
3392       if (! d_discriminator (di))
3393         return NULL;
3394       return d_make_comp (di, DEMANGLE_COMPONENT_LOCAL_NAME, function,
3395                           d_make_name (di, "string literal",
3396                                        sizeof "string literal" - 1));
3397     }
3398   else
3399     {
3400       struct demangle_component *name;
3401       int num = -1;
3402
3403       if (d_peek_char (di) == 'd')
3404         {
3405           /* Default argument scope: d <number> _.  */
3406           d_advance (di, 1);
3407           num = d_compact_number (di);
3408           if (num < 0)
3409             return NULL;
3410         }
3411
3412       name = d_name (di);
3413       if (name)
3414         switch (name->type)
3415           {
3416             /* Lambdas and unnamed types have internal discriminators.  */
3417           case DEMANGLE_COMPONENT_LAMBDA:
3418           case DEMANGLE_COMPONENT_UNNAMED_TYPE:
3419             break;
3420           default:
3421             if (! d_discriminator (di))
3422               return NULL;
3423           }
3424       if (num >= 0)
3425         name = d_make_default_arg (di, num, name);
3426       return d_make_comp (di, DEMANGLE_COMPONENT_LOCAL_NAME, function, name);
3427     }
3428 }
3429
3430 /* <discriminator> ::= _ <(non-negative) number>
3431
3432    We demangle the discriminator, but we don't print it out.  FIXME:
3433    We should print it out in verbose mode.  */
3434
3435 static int
3436 d_discriminator (struct d_info *di)
3437 {
3438   long discrim;
3439
3440   if (d_peek_char (di) != '_')
3441     return 1;
3442   d_advance (di, 1);
3443   discrim = d_number (di);
3444   if (discrim < 0)
3445     return 0;
3446   return 1;
3447 }
3448
3449 /* <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _ */
3450
3451 static struct demangle_component *
3452 d_lambda (struct d_info *di)
3453 {
3454   struct demangle_component *tl;
3455   struct demangle_component *ret;
3456   int num;
3457
3458   if (! d_check_char (di, 'U'))
3459     return NULL;
3460   if (! d_check_char (di, 'l'))
3461     return NULL;
3462
3463   tl = d_parmlist (di);
3464   if (tl == NULL)
3465     return NULL;
3466
3467   if (! d_check_char (di, 'E'))
3468     return NULL;
3469
3470   num = d_compact_number (di);
3471   if (num < 0)
3472     return NULL;
3473
3474   ret = d_make_empty (di);
3475   if (ret)
3476     {
3477       ret->type = DEMANGLE_COMPONENT_LAMBDA;
3478       ret->u.s_unary_num.sub = tl;
3479       ret->u.s_unary_num.num = num;
3480     }
3481
3482   if (! d_add_substitution (di, ret))
3483     return NULL;
3484
3485   return ret;
3486 }
3487
3488 /* <unnamed-type-name> ::= Ut [ <nonnegative number> ] _ */
3489
3490 static struct demangle_component *
3491 d_unnamed_type (struct d_info *di)
3492 {
3493   struct demangle_component *ret;
3494   long num;
3495
3496   if (! d_check_char (di, 'U'))
3497     return NULL;
3498   if (! d_check_char (di, 't'))
3499     return NULL;
3500
3501   num = d_compact_number (di);
3502   if (num < 0)
3503     return NULL;
3504
3505   ret = d_make_empty (di);
3506   if (ret)
3507     {
3508       ret->type = DEMANGLE_COMPONENT_UNNAMED_TYPE;
3509       ret->u.s_number.number = num;
3510     }
3511
3512   if (! d_add_substitution (di, ret))
3513     return NULL;
3514
3515   return ret;
3516 }
3517
3518 /* <clone-suffix> ::= [ . <clone-type-identifier> ] [ . <nonnegative number> ]*
3519 */
3520
3521 static struct demangle_component *
3522 d_clone_suffix (struct d_info *di, struct demangle_component *encoding)
3523 {
3524   const char *suffix = d_str (di);
3525   const char *pend = suffix;
3526   struct demangle_component *n;
3527
3528   if (*pend == '.' && (IS_LOWER (pend[1]) || pend[1] == '_'))
3529     {
3530       pend += 2;
3531       while (IS_LOWER (*pend) || *pend == '_')
3532         ++pend;
3533     }
3534   while (*pend == '.' && IS_DIGIT (pend[1]))
3535     {
3536       pend += 2;
3537       while (IS_DIGIT (*pend))
3538         ++pend;
3539     }
3540   d_advance (di, pend - suffix);
3541   n = d_make_name (di, suffix, pend - suffix);
3542   return d_make_comp (di, DEMANGLE_COMPONENT_CLONE, encoding, n);
3543 }
3544
3545 /* Add a new substitution.  */
3546
3547 static int
3548 d_add_substitution (struct d_info *di, struct demangle_component *dc)
3549 {
3550   if (dc == NULL)
3551     return 0;
3552   if (di->next_sub >= di->num_subs)
3553     return 0;
3554   di->subs[di->next_sub] = dc;
3555   ++di->next_sub;
3556   return 1;
3557 }
3558
3559 /* <substitution> ::= S <seq-id> _
3560                   ::= S_
3561                   ::= St
3562                   ::= Sa
3563                   ::= Sb
3564                   ::= Ss
3565                   ::= Si
3566                   ::= So
3567                   ::= Sd
3568
3569    If PREFIX is non-zero, then this type is being used as a prefix in
3570    a qualified name.  In this case, for the standard substitutions, we
3571    need to check whether we are being used as a prefix for a
3572    constructor or destructor, and return a full template name.
3573    Otherwise we will get something like std::iostream::~iostream()
3574    which does not correspond particularly well to any function which
3575    actually appears in the source.
3576 */
3577
3578 static const struct d_standard_sub_info standard_subs[] =
3579 {
3580   { 't', NL ("std"),
3581     NL ("std"),
3582     NULL, 0 },
3583   { 'a', NL ("std::allocator"),
3584     NL ("std::allocator"),
3585     NL ("allocator") },
3586   { 'b', NL ("std::basic_string"),
3587     NL ("std::basic_string"),
3588     NL ("basic_string") },
3589   { 's', NL ("std::string"),
3590     NL ("std::basic_string<char, std::char_traits<char>, std::allocator<char> >"),
3591     NL ("basic_string") },
3592   { 'i', NL ("std::istream"),
3593     NL ("std::basic_istream<char, std::char_traits<char> >"),
3594     NL ("basic_istream") },
3595   { 'o', NL ("std::ostream"),
3596     NL ("std::basic_ostream<char, std::char_traits<char> >"),
3597     NL ("basic_ostream") },
3598   { 'd', NL ("std::iostream"),
3599     NL ("std::basic_iostream<char, std::char_traits<char> >"),
3600     NL ("basic_iostream") }
3601 };
3602
3603 static struct demangle_component *
3604 d_substitution (struct d_info *di, int prefix)
3605 {
3606   char c;
3607
3608   if (! d_check_char (di, 'S'))
3609     return NULL;
3610
3611   c = d_next_char (di);
3612   if (c == '_' || IS_DIGIT (c) || IS_UPPER (c))
3613     {
3614       unsigned int id;
3615
3616       id = 0;
3617       if (c != '_')
3618         {
3619           do
3620             {
3621               unsigned int new_id;
3622
3623               if (IS_DIGIT (c))
3624                 new_id = id * 36 + c - '0';
3625               else if (IS_UPPER (c))
3626                 new_id = id * 36 + c - 'A' + 10;
3627               else
3628                 return NULL;
3629               if (new_id < id)
3630                 return NULL;
3631               id = new_id;
3632               c = d_next_char (di);
3633             }
3634           while (c != '_');
3635
3636           ++id;
3637         }
3638
3639       if (id >= (unsigned int) di->next_sub)
3640         return NULL;
3641
3642       ++di->did_subs;
3643
3644       return di->subs[id];
3645     }
3646   else
3647     {
3648       int verbose;
3649       const struct d_standard_sub_info *p;
3650       const struct d_standard_sub_info *pend;
3651
3652       verbose = (di->options & DMGL_VERBOSE) != 0;
3653       if (! verbose && prefix)
3654         {
3655           char peek;
3656
3657           peek = d_peek_char (di);
3658           if (peek == 'C' || peek == 'D')
3659             verbose = 1;
3660         }
3661
3662       pend = (&standard_subs[0]
3663               + sizeof standard_subs / sizeof standard_subs[0]);
3664       for (p = &standard_subs[0]; p < pend; ++p)
3665         {
3666           if (c == p->code)
3667             {
3668               const char *s;
3669               int len;
3670
3671               if (p->set_last_name != NULL)
3672                 di->last_name = d_make_sub (di, p->set_last_name,
3673                                             p->set_last_name_len);
3674               if (verbose)
3675                 {
3676                   s = p->full_expansion;
3677                   len = p->full_len;
3678                 }
3679               else
3680                 {
3681                   s = p->simple_expansion;
3682                   len = p->simple_len;
3683                 }
3684               di->expansion += len;
3685               return d_make_sub (di, s, len);
3686             }
3687         }
3688
3689       return NULL;
3690     }
3691 }
3692
3693 static void
3694 d_checkpoint (struct d_info *di, struct d_info_checkpoint *checkpoint)
3695 {
3696   checkpoint->n = di->n;
3697   checkpoint->next_comp = di->next_comp;
3698   checkpoint->next_sub = di->next_sub;
3699   checkpoint->did_subs = di->did_subs;
3700   checkpoint->expansion = di->expansion;
3701 }
3702
3703 static void
3704 d_backtrack (struct d_info *di, struct d_info_checkpoint *checkpoint)
3705 {
3706   di->n = checkpoint->n;
3707   di->next_comp = checkpoint->next_comp;
3708   di->next_sub = checkpoint->next_sub;
3709   di->did_subs = checkpoint->did_subs;
3710   di->expansion = checkpoint->expansion;
3711 }
3712
3713 /* Initialize a growable string.  */
3714
3715 static void
3716 d_growable_string_init (struct d_growable_string *dgs, size_t estimate)
3717 {
3718   dgs->buf = NULL;
3719   dgs->len = 0;
3720   dgs->alc = 0;
3721   dgs->allocation_failure = 0;
3722
3723   if (estimate > 0)
3724     d_growable_string_resize (dgs, estimate);
3725 }
3726
3727 /* Grow a growable string to a given size.  */
3728
3729 static inline void
3730 d_growable_string_resize (struct d_growable_string *dgs, size_t need)
3731 {
3732   size_t newalc;
3733   char *newbuf;
3734
3735   if (dgs->allocation_failure)
3736     return;
3737
3738   /* Start allocation at two bytes to avoid any possibility of confusion
3739      with the special value of 1 used as a return in *palc to indicate
3740      allocation failures.  */
3741   newalc = dgs->alc > 0 ? dgs->alc : 2;
3742   while (newalc < need)
3743     newalc <<= 1;
3744
3745   newbuf = (char *) realloc (dgs->buf, newalc);
3746   if (newbuf == NULL)
3747     {
3748       free (dgs->buf);
3749       dgs->buf = NULL;
3750       dgs->len = 0;
3751       dgs->alc = 0;
3752       dgs->allocation_failure = 1;
3753       return;
3754     }
3755   dgs->buf = newbuf;
3756   dgs->alc = newalc;
3757 }
3758
3759 /* Append a buffer to a growable string.  */
3760
3761 static inline void
3762 d_growable_string_append_buffer (struct d_growable_string *dgs,
3763                                  const char *s, size_t l)
3764 {
3765   size_t need;
3766
3767   need = dgs->len + l + 1;
3768   if (need > dgs->alc)
3769     d_growable_string_resize (dgs, need);
3770
3771   if (dgs->allocation_failure)
3772     return;
3773
3774   memcpy (dgs->buf + dgs->len, s, l);
3775   dgs->buf[dgs->len + l] = '\0';
3776   dgs->len += l;
3777 }
3778
3779 /* Bridge growable strings to the callback mechanism.  */
3780
3781 static void
3782 d_growable_string_callback_adapter (const char *s, size_t l, void *opaque)
3783 {
3784   struct d_growable_string *dgs = (struct d_growable_string*) opaque;
3785
3786   d_growable_string_append_buffer (dgs, s, l);
3787 }
3788
3789 /* Walk the tree, counting the number of templates encountered, and
3790    the number of times a scope might be saved.  These counts will be
3791    used to allocate data structures for d_print_comp, so the logic
3792    here must mirror the logic d_print_comp will use.  It is not
3793    important that the resulting numbers are exact, so long as they
3794    are larger than the actual numbers encountered.  */
3795
3796 static void
3797 d_count_templates_scopes (int *num_templates, int *num_scopes,
3798                           const struct demangle_component *dc)
3799 {
3800   if (dc == NULL)
3801     return;
3802
3803   switch (dc->type)
3804     {
3805     case DEMANGLE_COMPONENT_NAME:
3806     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
3807     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
3808     case DEMANGLE_COMPONENT_SUB_STD:
3809     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
3810     case DEMANGLE_COMPONENT_OPERATOR:
3811     case DEMANGLE_COMPONENT_CHARACTER:
3812     case DEMANGLE_COMPONENT_NUMBER:
3813     case DEMANGLE_COMPONENT_UNNAMED_TYPE:
3814       break;
3815
3816     case DEMANGLE_COMPONENT_TEMPLATE:
3817       (*num_templates)++;
3818       goto recurse_left_right;
3819
3820     case DEMANGLE_COMPONENT_REFERENCE:
3821     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
3822       if (d_left (dc)->type == DEMANGLE_COMPONENT_TEMPLATE_PARAM)
3823         (*num_scopes)++;
3824       goto recurse_left_right;
3825
3826     case DEMANGLE_COMPONENT_QUAL_NAME:
3827     case DEMANGLE_COMPONENT_LOCAL_NAME:
3828     case DEMANGLE_COMPONENT_TYPED_NAME:
3829     case DEMANGLE_COMPONENT_VTABLE:
3830     case DEMANGLE_COMPONENT_VTT:
3831     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
3832     case DEMANGLE_COMPONENT_TYPEINFO:
3833     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
3834     case DEMANGLE_COMPONENT_TYPEINFO_FN:
3835     case DEMANGLE_COMPONENT_THUNK:
3836     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
3837     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
3838     case DEMANGLE_COMPONENT_JAVA_CLASS:
3839     case DEMANGLE_COMPONENT_GUARD:
3840     case DEMANGLE_COMPONENT_TLS_INIT:
3841     case DEMANGLE_COMPONENT_TLS_WRAPPER:
3842     case DEMANGLE_COMPONENT_REFTEMP:
3843     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
3844     case DEMANGLE_COMPONENT_RESTRICT:
3845     case DEMANGLE_COMPONENT_VOLATILE:
3846     case DEMANGLE_COMPONENT_CONST:
3847     case DEMANGLE_COMPONENT_RESTRICT_THIS:
3848     case DEMANGLE_COMPONENT_VOLATILE_THIS:
3849     case DEMANGLE_COMPONENT_CONST_THIS:
3850     case DEMANGLE_COMPONENT_REFERENCE_THIS:
3851     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
3852     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
3853     case DEMANGLE_COMPONENT_POINTER:
3854     case DEMANGLE_COMPONENT_COMPLEX:
3855     case DEMANGLE_COMPONENT_IMAGINARY:
3856     case DEMANGLE_COMPONENT_VENDOR_TYPE:
3857     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
3858     case DEMANGLE_COMPONENT_ARRAY_TYPE:
3859     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
3860     case DEMANGLE_COMPONENT_FIXED_TYPE:
3861     case DEMANGLE_COMPONENT_VECTOR_TYPE:
3862     case DEMANGLE_COMPONENT_ARGLIST:
3863     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
3864     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
3865     case DEMANGLE_COMPONENT_CAST:
3866     case DEMANGLE_COMPONENT_NULLARY:
3867     case DEMANGLE_COMPONENT_UNARY:
3868     case DEMANGLE_COMPONENT_BINARY:
3869     case DEMANGLE_COMPONENT_BINARY_ARGS:
3870     case DEMANGLE_COMPONENT_TRINARY:
3871     case DEMANGLE_COMPONENT_TRINARY_ARG1:
3872     case DEMANGLE_COMPONENT_TRINARY_ARG2:
3873     case DEMANGLE_COMPONENT_LITERAL:
3874     case DEMANGLE_COMPONENT_LITERAL_NEG:
3875     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
3876     case DEMANGLE_COMPONENT_COMPOUND_NAME:
3877     case DEMANGLE_COMPONENT_DECLTYPE:
3878     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
3879     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
3880     case DEMANGLE_COMPONENT_PACK_EXPANSION:
3881     case DEMANGLE_COMPONENT_TAGGED_NAME:
3882     case DEMANGLE_COMPONENT_CLONE:
3883     recurse_left_right:
3884       d_count_templates_scopes (num_templates, num_scopes,
3885                                 d_left (dc));
3886       d_count_templates_scopes (num_templates, num_scopes,
3887                                 d_right (dc));
3888       break;
3889
3890     case DEMANGLE_COMPONENT_CTOR:
3891       d_count_templates_scopes (num_templates, num_scopes,
3892                                 dc->u.s_ctor.name);
3893       break;
3894
3895     case DEMANGLE_COMPONENT_DTOR:
3896       d_count_templates_scopes (num_templates, num_scopes,
3897                                 dc->u.s_dtor.name);
3898       break;
3899
3900     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
3901       d_count_templates_scopes (num_templates, num_scopes,
3902                                 dc->u.s_extended_operator.name);
3903       break;
3904
3905     case DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS:
3906     case DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS:
3907       d_count_templates_scopes (num_templates, num_scopes,
3908                                 d_left (dc));
3909       break;
3910
3911     case DEMANGLE_COMPONENT_LAMBDA:
3912     case DEMANGLE_COMPONENT_DEFAULT_ARG:
3913       d_count_templates_scopes (num_templates, num_scopes,
3914                                 dc->u.s_unary_num.sub);
3915       break;
3916     }
3917 }
3918
3919 /* Initialize a print information structure.  */
3920
3921 static void
3922 d_print_init (struct d_print_info *dpi, demangle_callbackref callback,
3923               void *opaque, const struct demangle_component *dc)
3924 {
3925   dpi->len = 0;
3926   dpi->last_char = '\0';
3927   dpi->templates = NULL;
3928   dpi->modifiers = NULL;
3929   dpi->pack_index = 0;
3930   dpi->flush_count = 0;
3931
3932   dpi->callback = callback;
3933   dpi->opaque = opaque;
3934
3935   dpi->demangle_failure = 0;
3936
3937   dpi->saved_scopes = NULL;
3938   dpi->next_saved_scope = 0;
3939   dpi->num_saved_scopes = 0;
3940
3941   dpi->copy_templates = NULL;
3942   dpi->next_copy_template = 0;
3943   dpi->num_copy_templates = 0;
3944
3945   d_count_templates_scopes (&dpi->num_copy_templates,
3946                             &dpi->num_saved_scopes, dc);
3947   dpi->num_copy_templates *= dpi->num_saved_scopes;
3948
3949   dpi->current_template = NULL;
3950 }
3951
3952 /* Indicate that an error occurred during printing, and test for error.  */
3953
3954 static inline void
3955 d_print_error (struct d_print_info *dpi)
3956 {
3957   dpi->demangle_failure = 1;
3958 }
3959
3960 static inline int
3961 d_print_saw_error (struct d_print_info *dpi)
3962 {
3963   return dpi->demangle_failure != 0;
3964 }
3965
3966 /* Flush buffered characters to the callback.  */
3967
3968 static inline void
3969 d_print_flush (struct d_print_info *dpi)
3970 {
3971   dpi->buf[dpi->len] = '\0';
3972   dpi->callback (dpi->buf, dpi->len, dpi->opaque);
3973   dpi->len = 0;
3974   dpi->flush_count++;
3975 }
3976
3977 /* Append characters and buffers for printing.  */
3978
3979 static inline void
3980 d_append_char (struct d_print_info *dpi, char c)
3981 {
3982   if (dpi->len == sizeof (dpi->buf) - 1)
3983     d_print_flush (dpi);
3984
3985   dpi->buf[dpi->len++] = c;
3986   dpi->last_char = c;
3987 }
3988
3989 static inline void
3990 d_append_buffer (struct d_print_info *dpi, const char *s, size_t l)
3991 {
3992   size_t i;
3993
3994   for (i = 0; i < l; i++)
3995     d_append_char (dpi, s[i]);
3996 }
3997
3998 static inline void
3999 d_append_string (struct d_print_info *dpi, const char *s)
4000 {
4001   d_append_buffer (dpi, s, strlen (s));
4002 }
4003
4004 static inline void
4005 d_append_num (struct d_print_info *dpi, long l)
4006 {
4007   char buf[25];
4008   sprintf (buf,"%ld", l);
4009   d_append_string (dpi, buf);
4010 }
4011
4012 static inline char
4013 d_last_char (struct d_print_info *dpi)
4014 {
4015   return dpi->last_char;
4016 }
4017
4018 /* Turn components into a human readable string.  OPTIONS is the
4019    options bits passed to the demangler.  DC is the tree to print.
4020    CALLBACK is a function to call to flush demangled string segments
4021    as they fill the intermediate buffer, and OPAQUE is a generalized
4022    callback argument.  On success, this returns 1.  On failure,
4023    it returns 0, indicating a bad parse.  It does not use heap
4024    memory to build an output string, so cannot encounter memory
4025    allocation failure.  */
4026
4027 CP_STATIC_IF_GLIBCPP_V3
4028 int
4029 cplus_demangle_print_callback (int options,
4030                                const struct demangle_component *dc,
4031                                demangle_callbackref callback, void *opaque)
4032 {
4033   struct d_print_info dpi;
4034
4035   d_print_init (&dpi, callback, opaque, dc);
4036
4037   {
4038 #ifdef CP_DYNAMIC_ARRAYS
4039     __extension__ struct d_saved_scope scopes[dpi.num_saved_scopes];
4040     __extension__ struct d_print_template temps[dpi.num_copy_templates];
4041
4042     dpi.saved_scopes = scopes;
4043     dpi.copy_templates = temps;
4044 #else
4045     dpi.saved_scopes = alloca (dpi.num_saved_scopes
4046                                * sizeof (*dpi.saved_scopes));
4047     dpi.copy_templates = alloca (dpi.num_copy_templates
4048                                  * sizeof (*dpi.copy_templates));
4049 #endif
4050
4051     d_print_comp (&dpi, options, dc);
4052   }
4053
4054   d_print_flush (&dpi);
4055
4056   return ! d_print_saw_error (&dpi);
4057 }
4058
4059 /* Turn components into a human readable string.  OPTIONS is the
4060    options bits passed to the demangler.  DC is the tree to print.
4061    ESTIMATE is a guess at the length of the result.  This returns a
4062    string allocated by malloc, or NULL on error.  On success, this
4063    sets *PALC to the size of the allocated buffer.  On failure, this
4064    sets *PALC to 0 for a bad parse, or to 1 for a memory allocation
4065    failure.  */
4066
4067 CP_STATIC_IF_GLIBCPP_V3
4068 char *
4069 cplus_demangle_print (int options, const struct demangle_component *dc,
4070                       int estimate, size_t *palc)
4071 {
4072   struct d_growable_string dgs;
4073
4074   d_growable_string_init (&dgs, estimate);
4075
4076   if (! cplus_demangle_print_callback (options, dc,
4077                                        d_growable_string_callback_adapter,
4078                                        &dgs))
4079     {
4080       free (dgs.buf);
4081       *palc = 0;
4082       return NULL;
4083     }
4084
4085   *palc = dgs.allocation_failure ? 1 : dgs.alc;
4086   return dgs.buf;
4087 }
4088
4089 /* Returns the I'th element of the template arglist ARGS, or NULL on
4090    failure.  */
4091
4092 static struct demangle_component *
4093 d_index_template_argument (struct demangle_component *args, int i)
4094 {
4095   struct demangle_component *a;
4096
4097   for (a = args;
4098        a != NULL;
4099        a = d_right (a))
4100     {
4101       if (a->type != DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
4102         return NULL;
4103       if (i <= 0)
4104         break;
4105       --i;
4106     }
4107   if (i != 0 || a == NULL)
4108     return NULL;
4109
4110   return d_left (a);
4111 }
4112
4113 /* Returns the template argument from the current context indicated by DC,
4114    which is a DEMANGLE_COMPONENT_TEMPLATE_PARAM, or NULL.  */
4115
4116 static struct demangle_component *
4117 d_lookup_template_argument (struct d_print_info *dpi,
4118                             const struct demangle_component *dc)
4119 {
4120   if (dpi->templates == NULL)
4121     {
4122       d_print_error (dpi);
4123       return NULL;
4124     }
4125         
4126   return d_index_template_argument
4127     (d_right (dpi->templates->template_decl),
4128      dc->u.s_number.number);
4129 }
4130
4131 /* Returns a template argument pack used in DC (any will do), or NULL.  */
4132
4133 static struct demangle_component *
4134 d_find_pack (struct d_print_info *dpi,
4135              const struct demangle_component *dc)
4136 {
4137   struct demangle_component *a;
4138   if (dc == NULL)
4139     return NULL;
4140
4141   switch (dc->type)
4142     {
4143     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
4144       a = d_lookup_template_argument (dpi, dc);
4145       if (a && a->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
4146         return a;
4147       return NULL;
4148
4149     case DEMANGLE_COMPONENT_PACK_EXPANSION:
4150       return NULL;
4151       
4152     case DEMANGLE_COMPONENT_LAMBDA:
4153     case DEMANGLE_COMPONENT_NAME:
4154     case DEMANGLE_COMPONENT_TAGGED_NAME:
4155     case DEMANGLE_COMPONENT_OPERATOR:
4156     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
4157     case DEMANGLE_COMPONENT_SUB_STD:
4158     case DEMANGLE_COMPONENT_CHARACTER:
4159     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
4160     case DEMANGLE_COMPONENT_UNNAMED_TYPE:
4161       return NULL;
4162
4163     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
4164       return d_find_pack (dpi, dc->u.s_extended_operator.name);
4165     case DEMANGLE_COMPONENT_CTOR:
4166       return d_find_pack (dpi, dc->u.s_ctor.name);
4167     case DEMANGLE_COMPONENT_DTOR:
4168       return d_find_pack (dpi, dc->u.s_dtor.name);
4169
4170     default:
4171       a = d_find_pack (dpi, d_left (dc));
4172       if (a)
4173         return a;
4174       return d_find_pack (dpi, d_right (dc));
4175     }
4176 }
4177
4178 /* Returns the length of the template argument pack DC.  */
4179
4180 static int
4181 d_pack_length (const struct demangle_component *dc)
4182 {
4183   int count = 0;
4184   while (dc && dc->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST
4185          && d_left (dc) != NULL)
4186     {
4187       ++count;
4188       dc = d_right (dc);
4189     }
4190   return count;
4191 }
4192
4193 /* DC is a component of a mangled expression.  Print it, wrapped in parens
4194    if needed.  */
4195
4196 static void
4197 d_print_subexpr (struct d_print_info *dpi, int options,
4198                  const struct demangle_component *dc)
4199 {
4200   int simple = 0;
4201   if (dc->type == DEMANGLE_COMPONENT_NAME
4202       || dc->type == DEMANGLE_COMPONENT_QUAL_NAME
4203       || dc->type == DEMANGLE_COMPONENT_INITIALIZER_LIST
4204       || dc->type == DEMANGLE_COMPONENT_FUNCTION_PARAM)
4205     simple = 1;
4206   if (!simple)
4207     d_append_char (dpi, '(');
4208   d_print_comp (dpi, options, dc);
4209   if (!simple)
4210     d_append_char (dpi, ')');
4211 }
4212
4213 /* Save the current scope.  */
4214
4215 static void
4216 d_save_scope (struct d_print_info *dpi,
4217               const struct demangle_component *container)
4218 {
4219   struct d_saved_scope *scope;
4220   struct d_print_template *src, **link;
4221
4222   if (dpi->next_saved_scope >= dpi->num_saved_scopes)
4223     {
4224       d_print_error (dpi);
4225       return;
4226     }
4227   scope = &dpi->saved_scopes[dpi->next_saved_scope];
4228   dpi->next_saved_scope++;
4229
4230   scope->container = container;
4231   link = &scope->templates;
4232
4233   for (src = dpi->templates; src != NULL; src = src->next)
4234     {
4235       struct d_print_template *dst;
4236
4237       if (dpi->next_copy_template >= dpi->num_copy_templates)
4238         {
4239           d_print_error (dpi);
4240           return;
4241         }
4242       dst = &dpi->copy_templates[dpi->next_copy_template];
4243       dpi->next_copy_template++;
4244
4245       dst->template_decl = src->template_decl;
4246       *link = dst;
4247       link = &dst->next;
4248     }
4249
4250   *link = NULL;
4251 }
4252
4253 /* Attempt to locate a previously saved scope.  Returns NULL if no
4254    corresponding saved scope was found.  */
4255
4256 static struct d_saved_scope *
4257 d_get_saved_scope (struct d_print_info *dpi,
4258                    const struct demangle_component *container)
4259 {
4260   int i;
4261
4262   for (i = 0; i < dpi->next_saved_scope; i++)
4263     if (dpi->saved_scopes[i].container == container)
4264       return &dpi->saved_scopes[i];
4265
4266   return NULL;
4267 }
4268
4269 /* Subroutine to handle components.  */
4270
4271 static void
4272 d_print_comp (struct d_print_info *dpi, int options,
4273               const struct demangle_component *dc)
4274 {
4275   /* Magic variable to let reference smashing skip over the next modifier
4276      without needing to modify *dc.  */
4277   const struct demangle_component *mod_inner = NULL;
4278
4279   /* Variable used to store the current templates while a previously
4280      captured scope is used.  */
4281   struct d_print_template *saved_templates;
4282
4283   /* Nonzero if templates have been stored in the above variable.  */
4284   int need_template_restore = 0;
4285
4286   if (dc == NULL)
4287     {
4288       d_print_error (dpi);
4289       return;
4290     }
4291   if (d_print_saw_error (dpi))
4292     return;
4293
4294   switch (dc->type)
4295     {
4296     case DEMANGLE_COMPONENT_NAME:
4297       if ((options & DMGL_JAVA) == 0)
4298         d_append_buffer (dpi, dc->u.s_name.s, dc->u.s_name.len);
4299       else
4300         d_print_java_identifier (dpi, dc->u.s_name.s, dc->u.s_name.len);
4301       return;
4302
4303     case DEMANGLE_COMPONENT_TAGGED_NAME:
4304       d_print_comp (dpi, options, d_left (dc));
4305       d_append_string (dpi, "[abi:");
4306       d_print_comp (dpi, options, d_right (dc));
4307       d_append_char (dpi, ']');
4308       return;
4309
4310     case DEMANGLE_COMPONENT_QUAL_NAME:
4311     case DEMANGLE_COMPONENT_LOCAL_NAME:
4312       d_print_comp (dpi, options, d_left (dc));
4313       if ((options & DMGL_JAVA) == 0)
4314         d_append_string (dpi, "::");
4315       else
4316         d_append_char (dpi, '.');
4317       {
4318         struct demangle_component *local_name = d_right (dc);
4319         if (local_name->type == DEMANGLE_COMPONENT_DEFAULT_ARG)
4320           {
4321             d_append_string (dpi, "{default arg#");
4322             d_append_num (dpi, local_name->u.s_unary_num.num + 1);
4323             d_append_string (dpi, "}::");
4324             local_name = local_name->u.s_unary_num.sub;
4325           }
4326         d_print_comp (dpi, options, local_name);
4327       }
4328       return;
4329
4330     case DEMANGLE_COMPONENT_TYPED_NAME:
4331       {
4332         struct d_print_mod *hold_modifiers;
4333         struct demangle_component *typed_name;
4334         struct d_print_mod adpm[4];
4335         unsigned int i;
4336         struct d_print_template dpt;
4337
4338         /* Pass the name down to the type so that it can be printed in
4339            the right place for the type.  We also have to pass down
4340            any CV-qualifiers, which apply to the this parameter.  */
4341         hold_modifiers = dpi->modifiers;
4342         dpi->modifiers = 0;
4343         i = 0;
4344         typed_name = d_left (dc);
4345         while (typed_name != NULL)
4346           {
4347             if (i >= sizeof adpm / sizeof adpm[0])
4348               {
4349                 d_print_error (dpi);
4350                 return;
4351               }
4352
4353             adpm[i].next = dpi->modifiers;
4354             dpi->modifiers = &adpm[i];
4355             adpm[i].mod = typed_name;
4356             adpm[i].printed = 0;
4357             adpm[i].templates = dpi->templates;
4358             ++i;
4359
4360             if (typed_name->type != DEMANGLE_COMPONENT_RESTRICT_THIS
4361                 && typed_name->type != DEMANGLE_COMPONENT_VOLATILE_THIS
4362                 && typed_name->type != DEMANGLE_COMPONENT_CONST_THIS
4363                 && typed_name->type != DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS
4364                 && typed_name->type != DEMANGLE_COMPONENT_REFERENCE_THIS)
4365               break;
4366
4367             typed_name = d_left (typed_name);
4368           }
4369
4370         if (typed_name == NULL)
4371           {
4372             d_print_error (dpi);
4373             return;
4374           }
4375
4376         /* If typed_name is a template, then it applies to the
4377            function type as well.  */
4378         if (typed_name->type == DEMANGLE_COMPONENT_TEMPLATE)
4379           {
4380             dpt.next = dpi->templates;
4381             dpi->templates = &dpt;
4382             dpt.template_decl = typed_name;
4383           }
4384
4385         /* If typed_name is a DEMANGLE_COMPONENT_LOCAL_NAME, then
4386            there may be CV-qualifiers on its right argument which
4387            really apply here; this happens when parsing a class which
4388            is local to a function.  */
4389         if (typed_name->type == DEMANGLE_COMPONENT_LOCAL_NAME)
4390           {
4391             struct demangle_component *local_name;
4392
4393             local_name = d_right (typed_name);
4394             if (local_name->type == DEMANGLE_COMPONENT_DEFAULT_ARG)
4395               local_name = local_name->u.s_unary_num.sub;
4396             while (local_name->type == DEMANGLE_COMPONENT_RESTRICT_THIS
4397                    || local_name->type == DEMANGLE_COMPONENT_VOLATILE_THIS
4398                    || local_name->type == DEMANGLE_COMPONENT_CONST_THIS
4399                    || local_name->type == DEMANGLE_COMPONENT_REFERENCE_THIS
4400                    || (local_name->type
4401                        == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS))
4402               {
4403                 if (i >= sizeof adpm / sizeof adpm[0])
4404                   {
4405                     d_print_error (dpi);
4406                     return;
4407                   }
4408
4409                 adpm[i] = adpm[i - 1];
4410                 adpm[i].next = &adpm[i - 1];
4411                 dpi->modifiers = &adpm[i];
4412
4413                 adpm[i - 1].mod = local_name;
4414                 adpm[i - 1].printed = 0;
4415                 adpm[i - 1].templates = dpi->templates;
4416                 ++i;
4417
4418                 local_name = d_left (local_name);
4419               }
4420           }
4421
4422         d_print_comp (dpi, options, d_right (dc));
4423
4424         if (typed_name->type == DEMANGLE_COMPONENT_TEMPLATE)
4425           dpi->templates = dpt.next;
4426
4427         /* If the modifiers didn't get printed by the type, print them
4428            now.  */
4429         while (i > 0)
4430           {
4431             --i;
4432             if (! adpm[i].printed)
4433               {
4434                 d_append_char (dpi, ' ');
4435                 d_print_mod (dpi, options, adpm[i].mod);
4436               }
4437           }
4438
4439         dpi->modifiers = hold_modifiers;
4440
4441         return;
4442       }
4443
4444     case DEMANGLE_COMPONENT_TEMPLATE:
4445       {
4446         struct d_print_mod *hold_dpm;
4447         struct demangle_component *dcl;
4448         const struct demangle_component *hold_current;
4449
4450         /* This template may need to be referenced by a cast operator
4451            contained in its subtree.  */
4452         hold_current = dpi->current_template;
4453         dpi->current_template = dc;
4454
4455         /* Don't push modifiers into a template definition.  Doing so
4456            could give the wrong definition for a template argument.
4457            Instead, treat the template essentially as a name.  */
4458
4459         hold_dpm = dpi->modifiers;
4460         dpi->modifiers = NULL;
4461
4462         dcl = d_left (dc);
4463
4464         if ((options & DMGL_JAVA) != 0
4465             && dcl->type == DEMANGLE_COMPONENT_NAME
4466             && dcl->u.s_name.len == 6
4467             && strncmp (dcl->u.s_name.s, "JArray", 6) == 0)
4468           {
4469             /* Special-case Java arrays, so that JArray<TYPE> appears
4470                instead as TYPE[].  */
4471
4472             d_print_comp (dpi, options, d_right (dc));
4473             d_append_string (dpi, "[]");
4474           }
4475         else
4476           {
4477             d_print_comp (dpi, options, dcl);
4478             if (d_last_char (dpi) == '<')
4479               d_append_char (dpi, ' ');
4480             d_append_char (dpi, '<');
4481             d_print_comp (dpi, options, d_right (dc));
4482             /* Avoid generating two consecutive '>' characters, to avoid
4483                the C++ syntactic ambiguity.  */
4484             if (d_last_char (dpi) == '>')
4485               d_append_char (dpi, ' ');
4486             d_append_char (dpi, '>');
4487           }
4488
4489         dpi->modifiers = hold_dpm;
4490         dpi->current_template = hold_current;
4491
4492         return;
4493       }
4494
4495     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
4496       {
4497         struct d_print_template *hold_dpt;
4498         struct demangle_component *a = d_lookup_template_argument (dpi, dc);
4499
4500         if (a && a->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
4501           a = d_index_template_argument (a, dpi->pack_index);
4502
4503         if (a == NULL)
4504           {
4505             d_print_error (dpi);
4506             return;
4507           }
4508
4509         /* While processing this parameter, we need to pop the list of
4510            templates.  This is because the template parameter may
4511            itself be a reference to a parameter of an outer
4512            template.  */
4513
4514         hold_dpt = dpi->templates;
4515         dpi->templates = hold_dpt->next;
4516
4517         d_print_comp (dpi, options, a);
4518
4519         dpi->templates = hold_dpt;
4520
4521         return;
4522       }
4523
4524     case DEMANGLE_COMPONENT_CTOR:
4525       d_print_comp (dpi, options, dc->u.s_ctor.name);
4526       return;
4527
4528     case DEMANGLE_COMPONENT_DTOR:
4529       d_append_char (dpi, '~');
4530       d_print_comp (dpi, options, dc->u.s_dtor.name);
4531       return;
4532
4533     case DEMANGLE_COMPONENT_VTABLE:
4534       d_append_string (dpi, "vtable for ");
4535       d_print_comp (dpi, options, d_left (dc));
4536       return;
4537
4538     case DEMANGLE_COMPONENT_VTT:
4539       d_append_string (dpi, "VTT for ");
4540       d_print_comp (dpi, options, d_left (dc));
4541       return;
4542
4543     case DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE:
4544       d_append_string (dpi, "construction vtable for ");
4545       d_print_comp (dpi, options, d_left (dc));
4546       d_append_string (dpi, "-in-");
4547       d_print_comp (dpi, options, d_right (dc));
4548       return;
4549
4550     case DEMANGLE_COMPONENT_TYPEINFO:
4551       d_append_string (dpi, "typeinfo for ");
4552       d_print_comp (dpi, options, d_left (dc));
4553       return;
4554
4555     case DEMANGLE_COMPONENT_TYPEINFO_NAME:
4556       d_append_string (dpi, "typeinfo name for ");
4557       d_print_comp (dpi, options, d_left (dc));
4558       return;
4559
4560     case DEMANGLE_COMPONENT_TYPEINFO_FN:
4561       d_append_string (dpi, "typeinfo fn for ");
4562       d_print_comp (dpi, options, d_left (dc));
4563       return;
4564
4565     case DEMANGLE_COMPONENT_THUNK:
4566       d_append_string (dpi, "non-virtual thunk to ");
4567       d_print_comp (dpi, options, d_left (dc));
4568       return;
4569
4570     case DEMANGLE_COMPONENT_VIRTUAL_THUNK:
4571       d_append_string (dpi, "virtual thunk to ");
4572       d_print_comp (dpi, options, d_left (dc));
4573       return;
4574
4575     case DEMANGLE_COMPONENT_COVARIANT_THUNK:
4576       d_append_string (dpi, "covariant return thunk to ");
4577       d_print_comp (dpi, options, d_left (dc));
4578       return;
4579
4580     case DEMANGLE_COMPONENT_JAVA_CLASS:
4581       d_append_string (dpi, "java Class for ");
4582       d_print_comp (dpi, options, d_left (dc));
4583       return;
4584
4585     case DEMANGLE_COMPONENT_GUARD:
4586       d_append_string (dpi, "guard variable for ");
4587       d_print_comp (dpi, options, d_left (dc));
4588       return;
4589
4590     case DEMANGLE_COMPONENT_TLS_INIT:
4591       d_append_string (dpi, "TLS init function for ");
4592       d_print_comp (dpi, options, d_left (dc));
4593       return;
4594
4595     case DEMANGLE_COMPONENT_TLS_WRAPPER:
4596       d_append_string (dpi, "TLS wrapper function for ");
4597       d_print_comp (dpi, options, d_left (dc));
4598       return;
4599
4600     case DEMANGLE_COMPONENT_REFTEMP:
4601       d_append_string (dpi, "reference temporary #");
4602       d_print_comp (dpi, options, d_right (dc));
4603       d_append_string (dpi, " for ");
4604       d_print_comp (dpi, options, d_left (dc));
4605       return;
4606
4607     case DEMANGLE_COMPONENT_HIDDEN_ALIAS:
4608       d_append_string (dpi, "hidden alias for ");
4609       d_print_comp (dpi, options, d_left (dc));
4610       return;
4611
4612     case DEMANGLE_COMPONENT_TRANSACTION_CLONE:
4613       d_append_string (dpi, "transaction clone for ");
4614       d_print_comp (dpi, options, d_left (dc));
4615       return;
4616
4617     case DEMANGLE_COMPONENT_NONTRANSACTION_CLONE:
4618       d_append_string (dpi, "non-transaction clone for ");
4619       d_print_comp (dpi, options, d_left (dc));
4620       return;
4621
4622     case DEMANGLE_COMPONENT_SUB_STD:
4623       d_append_buffer (dpi, dc->u.s_string.string, dc->u.s_string.len);
4624       return;
4625
4626     case DEMANGLE_COMPONENT_RESTRICT:
4627     case DEMANGLE_COMPONENT_VOLATILE:
4628     case DEMANGLE_COMPONENT_CONST:
4629       {
4630         struct d_print_mod *pdpm;
4631
4632         /* When printing arrays, it's possible to have cases where the
4633            same CV-qualifier gets pushed on the stack multiple times.
4634            We only need to print it once.  */
4635
4636         for (pdpm = dpi->modifiers; pdpm != NULL; pdpm = pdpm->next)
4637           {
4638             if (! pdpm->printed)
4639               {
4640                 if (pdpm->mod->type != DEMANGLE_COMPONENT_RESTRICT
4641                     && pdpm->mod->type != DEMANGLE_COMPONENT_VOLATILE
4642                     && pdpm->mod->type != DEMANGLE_COMPONENT_CONST)
4643                   break;
4644                 if (pdpm->mod->type == dc->type)
4645                   {
4646                     d_print_comp (dpi, options, d_left (dc));
4647                     return;
4648                   }
4649               }
4650           }
4651       }
4652       goto modifier;
4653
4654     case DEMANGLE_COMPONENT_REFERENCE:
4655     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
4656       {
4657         /* Handle reference smashing: & + && = &.  */
4658         const struct demangle_component *sub = d_left (dc);
4659         if (sub->type == DEMANGLE_COMPONENT_TEMPLATE_PARAM)
4660           {
4661             struct d_saved_scope *scope = d_get_saved_scope (dpi, sub);
4662             struct demangle_component *a;
4663
4664             if (scope == NULL)
4665               {
4666                 /* This is the first time SUB has been traversed.
4667                    We need to capture the current templates so
4668                    they can be restored if SUB is reentered as a
4669                    substitution.  */
4670                 d_save_scope (dpi, sub);
4671                 if (d_print_saw_error (dpi))
4672                   return;
4673               }
4674             else
4675               {
4676                 /* This traversal is reentering SUB as a substition.
4677                    Restore the original templates temporarily.  */
4678                 saved_templates = dpi->templates;
4679                 dpi->templates = scope->templates;
4680                 need_template_restore = 1;
4681               }
4682
4683             a = d_lookup_template_argument (dpi, sub);
4684             if (a && a->type == DEMANGLE_COMPONENT_TEMPLATE_ARGLIST)
4685               a = d_index_template_argument (a, dpi->pack_index);
4686
4687             if (a == NULL)
4688               {
4689                 if (need_template_restore)
4690                   dpi->templates = saved_templates;
4691
4692                 d_print_error (dpi);
4693                 return;
4694               }
4695
4696             sub = a;
4697           }
4698
4699         if (sub->type == DEMANGLE_COMPONENT_REFERENCE
4700             || sub->type == dc->type)
4701           dc = sub;
4702         else if (sub->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE)
4703           mod_inner = d_left (sub);
4704       }
4705       /* Fall through.  */
4706
4707     case DEMANGLE_COMPONENT_RESTRICT_THIS:
4708     case DEMANGLE_COMPONENT_VOLATILE_THIS:
4709     case DEMANGLE_COMPONENT_CONST_THIS:
4710     case DEMANGLE_COMPONENT_REFERENCE_THIS:
4711     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
4712     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
4713     case DEMANGLE_COMPONENT_POINTER:
4714     case DEMANGLE_COMPONENT_COMPLEX:
4715     case DEMANGLE_COMPONENT_IMAGINARY:
4716     modifier:
4717       {
4718         /* We keep a list of modifiers on the stack.  */
4719         struct d_print_mod dpm;
4720
4721         dpm.next = dpi->modifiers;
4722         dpi->modifiers = &dpm;
4723         dpm.mod = dc;
4724         dpm.printed = 0;
4725         dpm.templates = dpi->templates;
4726
4727         if (!mod_inner)
4728           mod_inner = d_left (dc);
4729
4730         d_print_comp (dpi, options, mod_inner);
4731
4732         /* If the modifier didn't get printed by the type, print it
4733            now.  */
4734         if (! dpm.printed)
4735           d_print_mod (dpi, options, dc);
4736
4737         dpi->modifiers = dpm.next;
4738
4739         if (need_template_restore)
4740           dpi->templates = saved_templates;
4741
4742         return;
4743       }
4744
4745     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
4746       if ((options & DMGL_JAVA) == 0)
4747         d_append_buffer (dpi, dc->u.s_builtin.type->name,
4748                          dc->u.s_builtin.type->len);
4749       else
4750         d_append_buffer (dpi, dc->u.s_builtin.type->java_name,
4751                          dc->u.s_builtin.type->java_len);
4752       return;
4753
4754     case DEMANGLE_COMPONENT_VENDOR_TYPE:
4755       d_print_comp (dpi, options, d_left (dc));
4756       return;
4757
4758     case DEMANGLE_COMPONENT_FUNCTION_TYPE:
4759       {
4760         if ((options & DMGL_RET_POSTFIX) != 0)
4761           d_print_function_type (dpi,
4762                                  options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
4763                                  dc, dpi->modifiers);
4764
4765         /* Print return type if present */
4766         if (d_left (dc) != NULL && (options & DMGL_RET_POSTFIX) != 0)
4767           d_print_comp (dpi, options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
4768                         d_left (dc));
4769         else if (d_left (dc) != NULL && (options & DMGL_RET_DROP) == 0)
4770           {
4771             struct d_print_mod dpm;
4772
4773             /* We must pass this type down as a modifier in order to
4774                print it in the right location.  */
4775             dpm.next = dpi->modifiers;
4776             dpi->modifiers = &dpm;
4777             dpm.mod = dc;
4778             dpm.printed = 0;
4779             dpm.templates = dpi->templates;
4780
4781             d_print_comp (dpi, options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
4782                           d_left (dc));
4783
4784             dpi->modifiers = dpm.next;
4785
4786             if (dpm.printed)
4787               return;
4788
4789             /* In standard prefix notation, there is a space between the
4790                return type and the function signature.  */
4791             if ((options & DMGL_RET_POSTFIX) == 0)
4792               d_append_char (dpi, ' ');
4793           }
4794
4795         if ((options & DMGL_RET_POSTFIX) == 0)
4796           d_print_function_type (dpi,
4797                                  options & ~(DMGL_RET_POSTFIX | DMGL_RET_DROP),
4798                                  dc, dpi->modifiers);
4799
4800         return;
4801       }
4802
4803     case DEMANGLE_COMPONENT_ARRAY_TYPE:
4804       {
4805         struct d_print_mod *hold_modifiers;
4806         struct d_print_mod adpm[4];
4807         unsigned int i;
4808         struct d_print_mod *pdpm;
4809
4810         /* We must pass this type down as a modifier in order to print
4811            multi-dimensional arrays correctly.  If the array itself is
4812            CV-qualified, we act as though the element type were
4813            CV-qualified.  We do this by copying the modifiers down
4814            rather than fiddling pointers, so that we don't wind up
4815            with a d_print_mod higher on the stack pointing into our
4816            stack frame after we return.  */
4817
4818         hold_modifiers = dpi->modifiers;
4819
4820         adpm[0].next = hold_modifiers;
4821         dpi->modifiers = &adpm[0];
4822         adpm[0].mod = dc;
4823         adpm[0].printed = 0;
4824         adpm[0].templates = dpi->templates;
4825
4826         i = 1;
4827         pdpm = hold_modifiers;
4828         while (pdpm != NULL
4829                && (pdpm->mod->type == DEMANGLE_COMPONENT_RESTRICT
4830                    || pdpm->mod->type == DEMANGLE_COMPONENT_VOLATILE
4831                    || pdpm->mod->type == DEMANGLE_COMPONENT_CONST))
4832           {
4833             if (! pdpm->printed)
4834               {
4835                 if (i >= sizeof adpm / sizeof adpm[0])
4836                   {
4837                     d_print_error (dpi);
4838                     return;
4839                   }
4840
4841                 adpm[i] = *pdpm;
4842                 adpm[i].next = dpi->modifiers;
4843                 dpi->modifiers = &adpm[i];
4844                 pdpm->printed = 1;
4845                 ++i;
4846               }
4847
4848             pdpm = pdpm->next;
4849           }
4850
4851         d_print_comp (dpi, options, d_right (dc));
4852
4853         dpi->modifiers = hold_modifiers;
4854
4855         if (adpm[0].printed)
4856           return;
4857
4858         while (i > 1)
4859           {
4860             --i;
4861             d_print_mod (dpi, options, adpm[i].mod);
4862           }
4863
4864         d_print_array_type (dpi, options, dc, dpi->modifiers);
4865
4866         return;
4867       }
4868
4869     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
4870     case DEMANGLE_COMPONENT_VECTOR_TYPE:
4871       {
4872         struct d_print_mod dpm;
4873
4874         dpm.next = dpi->modifiers;
4875         dpi->modifiers = &dpm;
4876         dpm.mod = dc;
4877         dpm.printed = 0;
4878         dpm.templates = dpi->templates;
4879
4880         d_print_comp (dpi, options, d_right (dc));
4881
4882         /* If the modifier didn't get printed by the type, print it
4883            now.  */
4884         if (! dpm.printed)
4885           d_print_mod (dpi, options, dc);
4886
4887         dpi->modifiers = dpm.next;
4888
4889         return;
4890       }
4891
4892     case DEMANGLE_COMPONENT_FIXED_TYPE:
4893       if (dc->u.s_fixed.sat)
4894         d_append_string (dpi, "_Sat ");
4895       /* Don't print "int _Accum".  */
4896       if (dc->u.s_fixed.length->u.s_builtin.type
4897           != &cplus_demangle_builtin_types['i'-'a'])
4898         {
4899           d_print_comp (dpi, options, dc->u.s_fixed.length);
4900           d_append_char (dpi, ' ');
4901         }
4902       if (dc->u.s_fixed.accum)
4903         d_append_string (dpi, "_Accum");
4904       else
4905         d_append_string (dpi, "_Fract");
4906       return;
4907
4908     case DEMANGLE_COMPONENT_ARGLIST:
4909     case DEMANGLE_COMPONENT_TEMPLATE_ARGLIST:
4910       if (d_left (dc) != NULL)
4911         d_print_comp (dpi, options, d_left (dc));
4912       if (d_right (dc) != NULL)
4913         {
4914           size_t len;
4915           unsigned long int flush_count;
4916           /* Make sure ", " isn't flushed by d_append_string, otherwise
4917              dpi->len -= 2 wouldn't work.  */
4918           if (dpi->len >= sizeof (dpi->buf) - 2)
4919             d_print_flush (dpi);
4920           d_append_string (dpi, ", ");
4921           len = dpi->len;
4922           flush_count = dpi->flush_count;
4923           d_print_comp (dpi, options, d_right (dc));
4924           /* If that didn't print anything (which can happen with empty
4925              template argument packs), remove the comma and space.  */
4926           if (dpi->flush_count == flush_count && dpi->len == len)
4927             dpi->len -= 2;
4928         }
4929       return;
4930
4931     case DEMANGLE_COMPONENT_INITIALIZER_LIST:
4932       {
4933         struct demangle_component *type = d_left (dc);
4934         struct demangle_component *list = d_right (dc);
4935
4936         if (type)
4937           d_print_comp (dpi, options, type);
4938         d_append_char (dpi, '{');
4939         d_print_comp (dpi, options, list);
4940         d_append_char (dpi, '}');
4941       }
4942       return;
4943
4944     case DEMANGLE_COMPONENT_OPERATOR:
4945       {
4946         const struct demangle_operator_info *op = dc->u.s_operator.op;
4947         int len = op->len;
4948
4949         d_append_string (dpi, "operator");
4950         /* Add a space before new/delete.  */
4951         if (IS_LOWER (op->name[0]))
4952           d_append_char (dpi, ' ');
4953         /* Omit a trailing space.  */
4954         if (op->name[len-1] == ' ')
4955           --len;
4956         d_append_buffer (dpi, op->name, len);
4957         return;
4958       }
4959
4960     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
4961       d_append_string (dpi, "operator ");
4962       d_print_comp (dpi, options, dc->u.s_extended_operator.name);
4963       return;
4964
4965     case DEMANGLE_COMPONENT_CAST:
4966       d_append_string (dpi, "operator ");
4967       d_print_cast (dpi, options, dc);
4968       return;
4969
4970     case DEMANGLE_COMPONENT_NULLARY:
4971       d_print_expr_op (dpi, options, d_left (dc));
4972       return;
4973
4974     case DEMANGLE_COMPONENT_UNARY:
4975       {
4976         struct demangle_component *op = d_left (dc);
4977         struct demangle_component *operand = d_right (dc);
4978         const char *code = NULL;
4979
4980         if (op->type == DEMANGLE_COMPONENT_OPERATOR)
4981           {
4982             code = op->u.s_operator.op->code;
4983             if (!strcmp (code, "ad"))
4984               {
4985                 /* Don't print the argument list for the address of a
4986                    function.  */
4987                 if (operand->type == DEMANGLE_COMPONENT_TYPED_NAME
4988                     && d_left (operand)->type == DEMANGLE_COMPONENT_QUAL_NAME
4989                     && d_right (operand)->type == DEMANGLE_COMPONENT_FUNCTION_TYPE)
4990                   operand = d_left (operand);
4991               }
4992             if (operand->type == DEMANGLE_COMPONENT_BINARY_ARGS)
4993               {
4994                 /* This indicates a suffix operator.  */
4995                 operand = d_left (operand);
4996                 d_print_subexpr (dpi, options, operand);
4997                 d_print_expr_op (dpi, options, op);
4998                 return;
4999               }
5000           }
5001
5002         if (op->type != DEMANGLE_COMPONENT_CAST)
5003           d_print_expr_op (dpi, options, op);
5004         else
5005           {
5006             d_append_char (dpi, '(');
5007             d_print_cast (dpi, options, op);
5008             d_append_char (dpi, ')');
5009           }
5010         if (code && !strcmp (code, "gs"))
5011           /* Avoid parens after '::'.  */
5012           d_print_comp (dpi, options, operand);
5013         else if (code && !strcmp (code, "st"))
5014           /* Always print parens for sizeof (type).  */
5015           {
5016             d_append_char (dpi, '(');
5017             d_print_comp (dpi, options, operand);
5018             d_append_char (dpi, ')');
5019           }
5020         else
5021           d_print_subexpr (dpi, options, operand);
5022       }
5023       return;
5024
5025     case DEMANGLE_COMPONENT_BINARY:
5026       if (d_right (dc)->type != DEMANGLE_COMPONENT_BINARY_ARGS)
5027         {
5028           d_print_error (dpi);
5029           return;
5030         }
5031
5032       if (op_is_new_cast (d_left (dc)))
5033         {
5034           d_print_expr_op (dpi, options, d_left (dc));
5035           d_append_char (dpi, '<');
5036           d_print_comp (dpi, options, d_left (d_right (dc)));
5037           d_append_string (dpi, ">(");
5038           d_print_comp (dpi, options, d_right (d_right (dc)));
5039           d_append_char (dpi, ')');
5040           return;
5041         }
5042
5043       /* We wrap an expression which uses the greater-than operator in
5044          an extra layer of parens so that it does not get confused
5045          with the '>' which ends the template parameters.  */
5046       if (d_left (dc)->type == DEMANGLE_COMPONENT_OPERATOR
5047           && d_left (dc)->u.s_operator.op->len == 1
5048           && d_left (dc)->u.s_operator.op->name[0] == '>')
5049         d_append_char (dpi, '(');
5050
5051       if (strcmp (d_left (dc)->u.s_operator.op->code, "cl") == 0
5052           && d_left (d_right (dc))->type == DEMANGLE_COMPONENT_TYPED_NAME)
5053         {
5054           /* Function call used in an expression should not have printed types
5055              of the function arguments.  Values of the function arguments still
5056              get printed below.  */
5057
5058           const struct demangle_component *func = d_left (d_right (dc));
5059
5060           if (d_right (func)->type != DEMANGLE_COMPONENT_FUNCTION_TYPE)
5061             d_print_error (dpi);
5062           d_print_subexpr (dpi, options, d_left (func));
5063         }
5064       else
5065         d_print_subexpr (dpi, options, d_left (d_right (dc)));
5066       if (strcmp (d_left (dc)->u.s_operator.op->code, "ix") == 0)
5067         {
5068           d_append_char (dpi, '[');
5069           d_print_comp (dpi, options, d_right (d_right (dc)));
5070           d_append_char (dpi, ']');
5071         }
5072       else
5073         {
5074           if (strcmp (d_left (dc)->u.s_operator.op->code, "cl") != 0)
5075             d_print_expr_op (dpi, options, d_left (dc));
5076           d_print_subexpr (dpi, options, d_right (d_right (dc)));
5077         }
5078
5079       if (d_left (dc)->type == DEMANGLE_COMPONENT_OPERATOR
5080           && d_left (dc)->u.s_operator.op->len == 1
5081           && d_left (dc)->u.s_operator.op->name[0] == '>')
5082         d_append_char (dpi, ')');
5083
5084       return;
5085
5086     case DEMANGLE_COMPONENT_BINARY_ARGS:
5087       /* We should only see this as part of DEMANGLE_COMPONENT_BINARY.  */
5088       d_print_error (dpi);
5089       return;
5090
5091     case DEMANGLE_COMPONENT_TRINARY:
5092       if (d_right (dc)->type != DEMANGLE_COMPONENT_TRINARY_ARG1
5093           || d_right (d_right (dc))->type != DEMANGLE_COMPONENT_TRINARY_ARG2)
5094         {
5095           d_print_error (dpi);
5096           return;
5097         }
5098       {
5099         struct demangle_component *op = d_left (dc);
5100         struct demangle_component *first = d_left (d_right (dc));
5101         struct demangle_component *second = d_left (d_right (d_right (dc)));
5102         struct demangle_component *third = d_right (d_right (d_right (dc)));
5103
5104         if (!strcmp (op->u.s_operator.op->code, "qu"))
5105           {
5106             d_print_subexpr (dpi, options, first);
5107             d_print_expr_op (dpi, options, op);
5108             d_print_subexpr (dpi, options, second);
5109             d_append_string (dpi, " : ");
5110             d_print_subexpr (dpi, options, third);
5111           }
5112         else
5113           {
5114             d_append_string (dpi, "new ");
5115             if (d_left (first) != NULL)
5116               {
5117                 d_print_subexpr (dpi, options, first);
5118                 d_append_char (dpi, ' ');
5119               }
5120             d_print_comp (dpi, options, second);
5121             if (third)
5122               d_print_subexpr (dpi, options, third);
5123           }
5124       }
5125       return;
5126
5127     case DEMANGLE_COMPONENT_TRINARY_ARG1:
5128     case DEMANGLE_COMPONENT_TRINARY_ARG2:
5129       /* We should only see these are part of DEMANGLE_COMPONENT_TRINARY.  */
5130       d_print_error (dpi);
5131       return;
5132
5133     case DEMANGLE_COMPONENT_LITERAL:
5134     case DEMANGLE_COMPONENT_LITERAL_NEG:
5135       {
5136         enum d_builtin_type_print tp;
5137
5138         /* For some builtin types, produce simpler output.  */
5139         tp = D_PRINT_DEFAULT;
5140         if (d_left (dc)->type == DEMANGLE_COMPONENT_BUILTIN_TYPE)
5141           {
5142             tp = d_left (dc)->u.s_builtin.type->print;
5143             switch (tp)
5144               {
5145               case D_PRINT_INT:
5146               case D_PRINT_UNSIGNED:
5147               case D_PRINT_LONG:
5148               case D_PRINT_UNSIGNED_LONG:
5149               case D_PRINT_LONG_LONG:
5150               case D_PRINT_UNSIGNED_LONG_LONG:
5151                 if (d_right (dc)->type == DEMANGLE_COMPONENT_NAME)
5152                   {
5153                     if (dc->type == DEMANGLE_COMPONENT_LITERAL_NEG)
5154                       d_append_char (dpi, '-');
5155                     d_print_comp (dpi, options, d_right (dc));
5156                     switch (tp)
5157                       {
5158                       default:
5159                         break;
5160                       case D_PRINT_UNSIGNED:
5161                         d_append_char (dpi, 'u');
5162                         break;
5163                       case D_PRINT_LONG:
5164                         d_append_char (dpi, 'l');
5165                         break;
5166                       case D_PRINT_UNSIGNED_LONG:
5167                         d_append_string (dpi, "ul");
5168                         break;
5169                       case D_PRINT_LONG_LONG:
5170                         d_append_string (dpi, "ll");
5171                         break;
5172                       case D_PRINT_UNSIGNED_LONG_LONG:
5173                         d_append_string (dpi, "ull");
5174                         break;
5175                       }
5176                     return;
5177                   }
5178                 break;
5179
5180               case D_PRINT_BOOL:
5181                 if (d_right (dc)->type == DEMANGLE_COMPONENT_NAME
5182                     && d_right (dc)->u.s_name.len == 1
5183                     && dc->type == DEMANGLE_COMPONENT_LITERAL)
5184                   {
5185                     switch (d_right (dc)->u.s_name.s[0])
5186                       {
5187                       case '0':
5188                         d_append_string (dpi, "false");
5189                         return;
5190                       case '1':
5191                         d_append_string (dpi, "true");
5192                         return;
5193                       default:
5194                         break;
5195                       }
5196                   }
5197                 break;
5198
5199               default:
5200                 break;
5201               }
5202           }
5203
5204         d_append_char (dpi, '(');
5205         d_print_comp (dpi, options, d_left (dc));
5206         d_append_char (dpi, ')');
5207         if (dc->type == DEMANGLE_COMPONENT_LITERAL_NEG)
5208           d_append_char (dpi, '-');
5209         if (tp == D_PRINT_FLOAT)
5210           d_append_char (dpi, '[');
5211         d_print_comp (dpi, options, d_right (dc));
5212         if (tp == D_PRINT_FLOAT)
5213           d_append_char (dpi, ']');
5214       }
5215       return;
5216
5217     case DEMANGLE_COMPONENT_NUMBER:
5218       d_append_num (dpi, dc->u.s_number.number);
5219       return;
5220
5221     case DEMANGLE_COMPONENT_JAVA_RESOURCE:
5222       d_append_string (dpi, "java resource ");
5223       d_print_comp (dpi, options, d_left (dc));
5224       return;
5225
5226     case DEMANGLE_COMPONENT_COMPOUND_NAME:
5227       d_print_comp (dpi, options, d_left (dc));
5228       d_print_comp (dpi, options, d_right (dc));
5229       return;
5230
5231     case DEMANGLE_COMPONENT_CHARACTER:
5232       d_append_char (dpi, dc->u.s_character.character);
5233       return;
5234
5235     case DEMANGLE_COMPONENT_DECLTYPE:
5236       d_append_string (dpi, "decltype (");
5237       d_print_comp (dpi, options, d_left (dc));
5238       d_append_char (dpi, ')');
5239       return;
5240
5241     case DEMANGLE_COMPONENT_PACK_EXPANSION:
5242       {
5243         int len;
5244         int i;
5245         struct demangle_component *a = d_find_pack (dpi, d_left (dc));
5246         if (a == NULL)
5247           {
5248             /* d_find_pack won't find anything if the only packs involved
5249                in this expansion are function parameter packs; in that
5250                case, just print the pattern and "...".  */
5251             d_print_subexpr (dpi, options, d_left (dc));
5252             d_append_string (dpi, "...");
5253             return;
5254           }
5255
5256         len = d_pack_length (a);
5257         dc = d_left (dc);
5258         for (i = 0; i < len; ++i)
5259           {
5260             dpi->pack_index = i;
5261             d_print_comp (dpi, options, dc);
5262             if (i < len-1)
5263               d_append_string (dpi, ", ");
5264           }
5265       }
5266       return;
5267
5268     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
5269       {
5270         long num = dc->u.s_number.number;
5271         if (num == 0)
5272           d_append_string (dpi, "this");
5273         else
5274           {
5275             d_append_string (dpi, "{parm#");
5276             d_append_num (dpi, num);
5277             d_append_char (dpi, '}');
5278           }
5279       }
5280       return;
5281
5282     case DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS:
5283       d_append_string (dpi, "global constructors keyed to ");
5284       d_print_comp (dpi, options, dc->u.s_binary.left);
5285       return;
5286
5287     case DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS:
5288       d_append_string (dpi, "global destructors keyed to ");
5289       d_print_comp (dpi, options, dc->u.s_binary.left);
5290       return;
5291
5292     case DEMANGLE_COMPONENT_LAMBDA:
5293       d_append_string (dpi, "{lambda(");
5294       d_print_comp (dpi, options, dc->u.s_unary_num.sub);
5295       d_append_string (dpi, ")#");
5296       d_append_num (dpi, dc->u.s_unary_num.num + 1);
5297       d_append_char (dpi, '}');
5298       return;
5299
5300     case DEMANGLE_COMPONENT_UNNAMED_TYPE:
5301       d_append_string (dpi, "{unnamed type#");
5302       d_append_num (dpi, dc->u.s_number.number + 1);
5303       d_append_char (dpi, '}');
5304       return;
5305
5306     case DEMANGLE_COMPONENT_CLONE:
5307       d_print_comp (dpi, options, d_left (dc));
5308       d_append_string (dpi, " [clone ");
5309       d_print_comp (dpi, options, d_right (dc));
5310       d_append_char (dpi, ']');
5311       return;
5312
5313     default:
5314       d_print_error (dpi);
5315       return;
5316     }
5317 }
5318
5319 /* Print a Java dentifier.  For Java we try to handle encoded extended
5320    Unicode characters.  The C++ ABI doesn't mention Unicode encoding,
5321    so we don't it for C++.  Characters are encoded as
5322    __U<hex-char>+_.  */
5323
5324 static void
5325 d_print_java_identifier (struct d_print_info *dpi, const char *name, int len)
5326 {
5327   const char *p;
5328   const char *end;
5329
5330   end = name + len;
5331   for (p = name; p < end; ++p)
5332     {
5333       if (end - p > 3
5334           && p[0] == '_'
5335           && p[1] == '_'
5336           && p[2] == 'U')
5337         {
5338           unsigned long c;
5339           const char *q;
5340
5341           c = 0;
5342           for (q = p + 3; q < end; ++q)
5343             {
5344               int dig;
5345
5346               if (IS_DIGIT (*q))
5347                 dig = *q - '0';
5348               else if (*q >= 'A' && *q <= 'F')
5349                 dig = *q - 'A' + 10;
5350               else if (*q >= 'a' && *q <= 'f')
5351                 dig = *q - 'a' + 10;
5352               else
5353                 break;
5354
5355               c = c * 16 + dig;
5356             }
5357           /* If the Unicode character is larger than 256, we don't try
5358              to deal with it here.  FIXME.  */
5359           if (q < end && *q == '_' && c < 256)
5360             {
5361               d_append_char (dpi, c);
5362               p = q;
5363               continue;
5364             }
5365         }
5366
5367       d_append_char (dpi, *p);
5368     }
5369 }
5370
5371 /* Print a list of modifiers.  SUFFIX is 1 if we are printing
5372    qualifiers on this after printing a function.  */
5373
5374 static void
5375 d_print_mod_list (struct d_print_info *dpi, int options,
5376                   struct d_print_mod *mods, int suffix)
5377 {
5378   struct d_print_template *hold_dpt;
5379
5380   if (mods == NULL || d_print_saw_error (dpi))
5381     return;
5382
5383   if (mods->printed
5384       || (! suffix
5385           && (mods->mod->type == DEMANGLE_COMPONENT_RESTRICT_THIS
5386               || mods->mod->type == DEMANGLE_COMPONENT_VOLATILE_THIS
5387               || mods->mod->type == DEMANGLE_COMPONENT_CONST_THIS
5388               || mods->mod->type == DEMANGLE_COMPONENT_REFERENCE_THIS
5389               || (mods->mod->type
5390                   == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS))))
5391     {
5392       d_print_mod_list (dpi, options, mods->next, suffix);
5393       return;
5394     }
5395
5396   mods->printed = 1;
5397
5398   hold_dpt = dpi->templates;
5399   dpi->templates = mods->templates;
5400
5401   if (mods->mod->type == DEMANGLE_COMPONENT_FUNCTION_TYPE)
5402     {
5403       d_print_function_type (dpi, options, mods->mod, mods->next);
5404       dpi->templates = hold_dpt;
5405       return;
5406     }
5407   else if (mods->mod->type == DEMANGLE_COMPONENT_ARRAY_TYPE)
5408     {
5409       d_print_array_type (dpi, options, mods->mod, mods->next);
5410       dpi->templates = hold_dpt;
5411       return;
5412     }
5413   else if (mods->mod->type == DEMANGLE_COMPONENT_LOCAL_NAME)
5414     {
5415       struct d_print_mod *hold_modifiers;
5416       struct demangle_component *dc;
5417
5418       /* When this is on the modifier stack, we have pulled any
5419          qualifiers off the right argument already.  Otherwise, we
5420          print it as usual, but don't let the left argument see any
5421          modifiers.  */
5422
5423       hold_modifiers = dpi->modifiers;
5424       dpi->modifiers = NULL;
5425       d_print_comp (dpi, options, d_left (mods->mod));
5426       dpi->modifiers = hold_modifiers;
5427
5428       if ((options & DMGL_JAVA) == 0)
5429         d_append_string (dpi, "::");
5430       else
5431         d_append_char (dpi, '.');
5432
5433       dc = d_right (mods->mod);
5434
5435       if (dc->type == DEMANGLE_COMPONENT_DEFAULT_ARG)
5436         {
5437           d_append_string (dpi, "{default arg#");
5438           d_append_num (dpi, dc->u.s_unary_num.num + 1);
5439           d_append_string (dpi, "}::");
5440           dc = dc->u.s_unary_num.sub;
5441         }
5442
5443       while (dc->type == DEMANGLE_COMPONENT_RESTRICT_THIS
5444              || dc->type == DEMANGLE_COMPONENT_VOLATILE_THIS
5445              || dc->type == DEMANGLE_COMPONENT_CONST_THIS
5446              || dc->type == DEMANGLE_COMPONENT_REFERENCE_THIS
5447              || dc->type == DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS)
5448         dc = d_left (dc);
5449
5450       d_print_comp (dpi, options, dc);
5451
5452       dpi->templates = hold_dpt;
5453       return;
5454     }
5455
5456   d_print_mod (dpi, options, mods->mod);
5457
5458   dpi->templates = hold_dpt;
5459
5460   d_print_mod_list (dpi, options, mods->next, suffix);
5461 }
5462
5463 /* Print a modifier.  */
5464
5465 static void
5466 d_print_mod (struct d_print_info *dpi, int options,
5467              const struct demangle_component *mod)
5468 {
5469   switch (mod->type)
5470     {
5471     case DEMANGLE_COMPONENT_RESTRICT:
5472     case DEMANGLE_COMPONENT_RESTRICT_THIS:
5473       d_append_string (dpi, " restrict");
5474       return;
5475     case DEMANGLE_COMPONENT_VOLATILE:
5476     case DEMANGLE_COMPONENT_VOLATILE_THIS:
5477       d_append_string (dpi, " volatile");
5478       return;
5479     case DEMANGLE_COMPONENT_CONST:
5480     case DEMANGLE_COMPONENT_CONST_THIS:
5481       d_append_string (dpi, " const");
5482       return;
5483     case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
5484       d_append_char (dpi, ' ');
5485       d_print_comp (dpi, options, d_right (mod));
5486       return;
5487     case DEMANGLE_COMPONENT_POINTER:
5488       /* There is no pointer symbol in Java.  */
5489       if ((options & DMGL_JAVA) == 0)
5490         d_append_char (dpi, '*');
5491       return;
5492     case DEMANGLE_COMPONENT_REFERENCE_THIS:
5493       /* For the ref-qualifier, put a space before the &.  */
5494       d_append_char (dpi, ' ');
5495     case DEMANGLE_COMPONENT_REFERENCE:
5496       d_append_char (dpi, '&');
5497       return;
5498     case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
5499       d_append_char (dpi, ' ');
5500     case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
5501       d_append_string (dpi, "&&");
5502       return;
5503     case DEMANGLE_COMPONENT_COMPLEX:
5504       d_append_string (dpi, "complex ");
5505       return;
5506     case DEMANGLE_COMPONENT_IMAGINARY:
5507       d_append_string (dpi, "imaginary ");
5508       return;
5509     case DEMANGLE_COMPONENT_PTRMEM_TYPE:
5510       if (d_last_char (dpi) != '(')
5511         d_append_char (dpi, ' ');
5512       d_print_comp (dpi, options, d_left (mod));
5513       d_append_string (dpi, "::*");
5514       return;
5515     case DEMANGLE_COMPONENT_TYPED_NAME:
5516       d_print_comp (dpi, options, d_left (mod));
5517       return;
5518     case DEMANGLE_COMPONENT_VECTOR_TYPE:
5519       d_append_string (dpi, " __vector(");
5520       d_print_comp (dpi, options, d_left (mod));
5521       d_append_char (dpi, ')');
5522       return;
5523
5524     default:
5525       /* Otherwise, we have something that won't go back on the
5526          modifier stack, so we can just print it.  */
5527       d_print_comp (dpi, options, mod);
5528       return;
5529     }
5530 }
5531
5532 /* Print a function type, except for the return type.  */
5533
5534 static void
5535 d_print_function_type (struct d_print_info *dpi, int options,
5536                        const struct demangle_component *dc,
5537                        struct d_print_mod *mods)
5538 {
5539   int need_paren;
5540   int need_space;
5541   struct d_print_mod *p;
5542   struct d_print_mod *hold_modifiers;
5543
5544   need_paren = 0;
5545   need_space = 0;
5546   for (p = mods; p != NULL; p = p->next)
5547     {
5548       if (p->printed)
5549         break;
5550
5551       switch (p->mod->type)
5552         {
5553         case DEMANGLE_COMPONENT_POINTER:
5554         case DEMANGLE_COMPONENT_REFERENCE:
5555         case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
5556           need_paren = 1;
5557           break;
5558         case DEMANGLE_COMPONENT_RESTRICT:
5559         case DEMANGLE_COMPONENT_VOLATILE:
5560         case DEMANGLE_COMPONENT_CONST:
5561         case DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL:
5562         case DEMANGLE_COMPONENT_COMPLEX:
5563         case DEMANGLE_COMPONENT_IMAGINARY:
5564         case DEMANGLE_COMPONENT_PTRMEM_TYPE:
5565           need_space = 1;
5566           need_paren = 1;
5567           break;
5568         case DEMANGLE_COMPONENT_RESTRICT_THIS:
5569         case DEMANGLE_COMPONENT_VOLATILE_THIS:
5570         case DEMANGLE_COMPONENT_CONST_THIS:
5571         case DEMANGLE_COMPONENT_REFERENCE_THIS:
5572         case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
5573           break;
5574         default:
5575           break;
5576         }
5577       if (need_paren)
5578         break;
5579     }
5580
5581   if (need_paren)
5582     {
5583       if (! need_space)
5584         {
5585           if (d_last_char (dpi) != '('
5586               && d_last_char (dpi) != '*')
5587             need_space = 1;
5588         }
5589       if (need_space && d_last_char (dpi) != ' ')
5590         d_append_char (dpi, ' ');
5591       d_append_char (dpi, '(');
5592     }
5593
5594   hold_modifiers = dpi->modifiers;
5595   dpi->modifiers = NULL;
5596
5597   d_print_mod_list (dpi, options, mods, 0);
5598
5599   if (need_paren)
5600     d_append_char (dpi, ')');
5601
5602   d_append_char (dpi, '(');
5603
5604   if (d_right (dc) != NULL)
5605     d_print_comp (dpi, options, d_right (dc));
5606
5607   d_append_char (dpi, ')');
5608
5609   d_print_mod_list (dpi, options, mods, 1);
5610
5611   dpi->modifiers = hold_modifiers;
5612 }
5613
5614 /* Print an array type, except for the element type.  */
5615
5616 static void
5617 d_print_array_type (struct d_print_info *dpi, int options,
5618                     const struct demangle_component *dc,
5619                     struct d_print_mod *mods)
5620 {
5621   int need_space;
5622
5623   need_space = 1;
5624   if (mods != NULL)
5625     {
5626       int need_paren;
5627       struct d_print_mod *p;
5628
5629       need_paren = 0;
5630       for (p = mods; p != NULL; p = p->next)
5631         {
5632           if (! p->printed)
5633             {
5634               if (p->mod->type == DEMANGLE_COMPONENT_ARRAY_TYPE)
5635                 {
5636                   need_space = 0;
5637                   break;
5638                 }
5639               else
5640                 {
5641                   need_paren = 1;
5642                   need_space = 1;
5643                   break;
5644                 }
5645             }
5646         }
5647
5648       if (need_paren)
5649         d_append_string (dpi, " (");
5650
5651       d_print_mod_list (dpi, options, mods, 0);
5652
5653       if (need_paren)
5654         d_append_char (dpi, ')');
5655     }
5656
5657   if (need_space)
5658     d_append_char (dpi, ' ');
5659
5660   d_append_char (dpi, '[');
5661
5662   if (d_left (dc) != NULL)
5663     d_print_comp (dpi, options, d_left (dc));
5664
5665   d_append_char (dpi, ']');
5666 }
5667
5668 /* Print an operator in an expression.  */
5669
5670 static void
5671 d_print_expr_op (struct d_print_info *dpi, int options,
5672                  const struct demangle_component *dc)
5673 {
5674   if (dc->type == DEMANGLE_COMPONENT_OPERATOR)
5675     d_append_buffer (dpi, dc->u.s_operator.op->name,
5676                      dc->u.s_operator.op->len);
5677   else
5678     d_print_comp (dpi, options, dc);
5679 }
5680
5681 /* Print a cast.  */
5682
5683 static void
5684 d_print_cast (struct d_print_info *dpi, int options,
5685               const struct demangle_component *dc)
5686 {
5687   struct d_print_template dpt;
5688
5689   /* For a cast operator, we need the template parameters from
5690      the enclosing template in scope for processing the type.  */
5691   if (dpi->current_template != NULL)
5692     {
5693       dpt.next = dpi->templates;
5694       dpi->templates = &dpt;
5695       dpt.template_decl = dpi->current_template;
5696     }
5697
5698   if (d_left (dc)->type != DEMANGLE_COMPONENT_TEMPLATE)
5699     {
5700       d_print_comp (dpi, options, d_left (dc));
5701       if (dpi->current_template != NULL)
5702         dpi->templates = dpt.next;
5703     }
5704   else
5705     {
5706       d_print_comp (dpi, options, d_left (d_left (dc)));
5707
5708       /* For a templated cast operator, we need to remove the template
5709          parameters from scope after printing the operator name,
5710          so we need to handle the template printing here.  */
5711       if (dpi->current_template != NULL)
5712         dpi->templates = dpt.next;
5713
5714       if (d_last_char (dpi) == '<')
5715         d_append_char (dpi, ' ');
5716       d_append_char (dpi, '<');
5717       d_print_comp (dpi, options, d_right (d_left (dc)));
5718       /* Avoid generating two consecutive '>' characters, to avoid
5719          the C++ syntactic ambiguity.  */
5720       if (d_last_char (dpi) == '>')
5721         d_append_char (dpi, ' ');
5722       d_append_char (dpi, '>');
5723     }
5724 }
5725
5726 /* Initialize the information structure we use to pass around
5727    information.  */
5728
5729 CP_STATIC_IF_GLIBCPP_V3
5730 void
5731 cplus_demangle_init_info (const char *mangled, int options, size_t len,
5732                           struct d_info *di)
5733 {
5734   di->s = mangled;
5735   di->send = mangled + len;
5736   di->options = options;
5737
5738   di->n = mangled;
5739
5740   /* We can not need more components than twice the number of chars in
5741      the mangled string.  Most components correspond directly to
5742      chars, but the ARGLIST types are exceptions.  */
5743   di->num_comps = 2 * len;
5744   di->next_comp = 0;
5745
5746   /* Similarly, we can not need more substitutions than there are
5747      chars in the mangled string.  */
5748   di->num_subs = len;
5749   di->next_sub = 0;
5750   di->did_subs = 0;
5751
5752   di->last_name = NULL;
5753
5754   di->expansion = 0;
5755   di->is_expression = 0;
5756   di->is_conversion = 0;
5757 }
5758
5759 /* Internal implementation for the demangler.  If MANGLED is a g++ v3 ABI
5760    mangled name, return strings in repeated callback giving the demangled
5761    name.  OPTIONS is the usual libiberty demangler options.  On success,
5762    this returns 1.  On failure, returns 0.  */
5763
5764 static int
5765 d_demangle_callback (const char *mangled, int options,
5766                      demangle_callbackref callback, void *opaque)
5767 {
5768   enum
5769     {
5770       DCT_TYPE,
5771       DCT_MANGLED,
5772       DCT_GLOBAL_CTORS,
5773       DCT_GLOBAL_DTORS
5774     }
5775   type;
5776   struct d_info di;
5777   struct demangle_component *dc;
5778   int status;
5779
5780   if (mangled[0] == '_' && mangled[1] == 'Z')
5781     type = DCT_MANGLED;
5782   else if (strncmp (mangled, "_GLOBAL_", 8) == 0
5783            && (mangled[8] == '.' || mangled[8] == '_' || mangled[8] == '$')
5784            && (mangled[9] == 'D' || mangled[9] == 'I')
5785            && mangled[10] == '_')
5786     type = mangled[9] == 'I' ? DCT_GLOBAL_CTORS : DCT_GLOBAL_DTORS;
5787   else
5788     {
5789       if ((options & DMGL_TYPES) == 0)
5790         return 0;
5791       type = DCT_TYPE;
5792     }
5793
5794   cplus_demangle_init_info (mangled, options, strlen (mangled), &di);
5795
5796   {
5797 #ifdef CP_DYNAMIC_ARRAYS
5798     __extension__ struct demangle_component comps[di.num_comps];
5799     __extension__ struct demangle_component *subs[di.num_subs];
5800
5801     di.comps = comps;
5802     di.subs = subs;
5803 #else
5804     di.comps = alloca (di.num_comps * sizeof (*di.comps));
5805     di.subs = alloca (di.num_subs * sizeof (*di.subs));
5806 #endif
5807
5808     switch (type)
5809       {
5810       case DCT_TYPE:
5811         dc = cplus_demangle_type (&di);
5812         break;
5813       case DCT_MANGLED:
5814         dc = cplus_demangle_mangled_name (&di, 1);
5815         break;
5816       case DCT_GLOBAL_CTORS:
5817       case DCT_GLOBAL_DTORS:
5818         d_advance (&di, 11);
5819         dc = d_make_comp (&di,
5820                           (type == DCT_GLOBAL_CTORS
5821                            ? DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS
5822                            : DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS),
5823                           d_make_demangle_mangled_name (&di, d_str (&di)),
5824                           NULL);
5825         d_advance (&di, strlen (d_str (&di)));
5826         break;
5827       }
5828
5829     /* If DMGL_PARAMS is set, then if we didn't consume the entire
5830        mangled string, then we didn't successfully demangle it.  If
5831        DMGL_PARAMS is not set, we didn't look at the trailing
5832        parameters.  */
5833     if (((options & DMGL_PARAMS) != 0) && d_peek_char (&di) != '\0')
5834       dc = NULL;
5835
5836 #ifdef CP_DEMANGLE_DEBUG
5837     d_dump (dc, 0);
5838 #endif
5839
5840     status = (dc != NULL)
5841              ? cplus_demangle_print_callback (options, dc, callback, opaque)
5842              : 0;
5843   }
5844
5845   return status;
5846 }
5847
5848 /* Entry point for the demangler.  If MANGLED is a g++ v3 ABI mangled
5849    name, return a buffer allocated with malloc holding the demangled
5850    name.  OPTIONS is the usual libiberty demangler options.  On
5851    success, this sets *PALC to the allocated size of the returned
5852    buffer.  On failure, this sets *PALC to 0 for a bad name, or 1 for
5853    a memory allocation failure, and returns NULL.  */
5854
5855 static char *
5856 d_demangle (const char *mangled, int options, size_t *palc)
5857 {
5858   struct d_growable_string dgs;
5859   int status;
5860
5861   d_growable_string_init (&dgs, 0);
5862
5863   status = d_demangle_callback (mangled, options,
5864                                 d_growable_string_callback_adapter, &dgs);
5865   if (status == 0)
5866     {
5867       free (dgs.buf);
5868       *palc = 0;
5869       return NULL;
5870     }
5871
5872   *palc = dgs.allocation_failure ? 1 : dgs.alc;
5873   return dgs.buf;
5874 }
5875
5876 #if defined(IN_LIBGCC2) || defined(IN_GLIBCPP_V3)
5877
5878 extern char *__cxa_demangle (const char *, char *, size_t *, int *);
5879
5880 /* ia64 ABI-mandated entry point in the C++ runtime library for
5881    performing demangling.  MANGLED_NAME is a NUL-terminated character
5882    string containing the name to be demangled.
5883
5884    OUTPUT_BUFFER is a region of memory, allocated with malloc, of
5885    *LENGTH bytes, into which the demangled name is stored.  If
5886    OUTPUT_BUFFER is not long enough, it is expanded using realloc.
5887    OUTPUT_BUFFER may instead be NULL; in that case, the demangled name
5888    is placed in a region of memory allocated with malloc.
5889
5890    If LENGTH is non-NULL, the length of the buffer containing the
5891    demangled name, is placed in *LENGTH.
5892
5893    The return value is a pointer to the start of the NUL-terminated
5894    demangled name, or NULL if the demangling fails.  The caller is
5895    responsible for deallocating this memory using free.
5896
5897    *STATUS is set to one of the following values:
5898       0: The demangling operation succeeded.
5899      -1: A memory allocation failure occurred.
5900      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
5901      -3: One of the arguments is invalid.
5902
5903    The demangling is performed using the C++ ABI mangling rules, with
5904    GNU extensions.  */
5905
5906 char *
5907 __cxa_demangle (const char *mangled_name, char *output_buffer,
5908                 size_t *length, int *status)
5909 {
5910   char *demangled;
5911   size_t alc;
5912
5913   if (mangled_name == NULL)
5914     {
5915       if (status != NULL)
5916         *status = -3;
5917       return NULL;
5918     }
5919
5920   if (output_buffer != NULL && length == NULL)
5921     {
5922       if (status != NULL)
5923         *status = -3;
5924       return NULL;
5925     }
5926
5927   demangled = d_demangle (mangled_name, DMGL_PARAMS | DMGL_TYPES, &alc);
5928
5929   if (demangled == NULL)
5930     {
5931       if (status != NULL)
5932         {
5933           if (alc == 1)
5934             *status = -1;
5935           else
5936             *status = -2;
5937         }
5938       return NULL;
5939     }
5940
5941   if (output_buffer == NULL)
5942     {
5943       if (length != NULL)
5944         *length = alc;
5945     }
5946   else
5947     {
5948       if (strlen (demangled) < *length)
5949         {
5950           strcpy (output_buffer, demangled);
5951           free (demangled);
5952           demangled = output_buffer;
5953         }
5954       else
5955         {
5956           free (output_buffer);
5957           *length = alc;
5958         }
5959     }
5960
5961   if (status != NULL)
5962     *status = 0;
5963
5964   return demangled;
5965 }
5966
5967 extern int __gcclibcxx_demangle_callback (const char *,
5968                                           void (*)
5969                                             (const char *, size_t, void *),
5970                                           void *);
5971
5972 /* Alternative, allocationless entry point in the C++ runtime library
5973    for performing demangling.  MANGLED_NAME is a NUL-terminated character
5974    string containing the name to be demangled.
5975
5976    CALLBACK is a callback function, called with demangled string
5977    segments as demangling progresses; it is called at least once,
5978    but may be called more than once.  OPAQUE is a generalized pointer
5979    used as a callback argument.
5980
5981    The return code is one of the following values, equivalent to
5982    the STATUS values of __cxa_demangle() (excluding -1, since this
5983    function performs no memory allocations):
5984       0: The demangling operation succeeded.
5985      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
5986      -3: One of the arguments is invalid.
5987
5988    The demangling is performed using the C++ ABI mangling rules, with
5989    GNU extensions.  */
5990
5991 int
5992 __gcclibcxx_demangle_callback (const char *mangled_name,
5993                                void (*callback) (const char *, size_t, void *),
5994                                void *opaque)
5995 {
5996   int status;
5997
5998   if (mangled_name == NULL || callback == NULL)
5999     return -3;
6000
6001   status = d_demangle_callback (mangled_name, DMGL_PARAMS | DMGL_TYPES,
6002                                 callback, opaque);
6003   if (status == 0)
6004     return -2;
6005
6006   return 0;
6007 }
6008
6009 #else /* ! (IN_LIBGCC2 || IN_GLIBCPP_V3) */
6010
6011 /* Entry point for libiberty demangler.  If MANGLED is a g++ v3 ABI
6012    mangled name, return a buffer allocated with malloc holding the
6013    demangled name.  Otherwise, return NULL.  */
6014
6015 char *
6016 cplus_demangle_v3 (const char *mangled, int options)
6017 {
6018   size_t alc;
6019
6020   return d_demangle (mangled, options, &alc);
6021 }
6022
6023 int
6024 cplus_demangle_v3_callback (const char *mangled, int options,
6025                             demangle_callbackref callback, void *opaque)
6026 {
6027   return d_demangle_callback (mangled, options, callback, opaque);
6028 }
6029
6030 /* Demangle a Java symbol.  Java uses a subset of the V3 ABI C++ mangling 
6031    conventions, but the output formatting is a little different.
6032    This instructs the C++ demangler not to emit pointer characters ("*"), to
6033    use Java's namespace separator symbol ("." instead of "::"), and to output
6034    JArray<TYPE> as TYPE[].  */
6035
6036 char *
6037 java_demangle_v3 (const char *mangled)
6038 {
6039   size_t alc;
6040
6041   return d_demangle (mangled, DMGL_JAVA | DMGL_PARAMS | DMGL_RET_POSTFIX, &alc);
6042 }
6043
6044 int
6045 java_demangle_v3_callback (const char *mangled,
6046                            demangle_callbackref callback, void *opaque)
6047 {
6048   return d_demangle_callback (mangled,
6049                               DMGL_JAVA | DMGL_PARAMS | DMGL_RET_POSTFIX,
6050                               callback, opaque);
6051 }
6052
6053 #endif /* IN_LIBGCC2 || IN_GLIBCPP_V3 */
6054
6055 #ifndef IN_GLIBCPP_V3
6056
6057 /* Demangle a string in order to find out whether it is a constructor
6058    or destructor.  Return non-zero on success.  Set *CTOR_KIND and
6059    *DTOR_KIND appropriately.  */
6060
6061 static int
6062 is_ctor_or_dtor (const char *mangled,
6063                  enum gnu_v3_ctor_kinds *ctor_kind,
6064                  enum gnu_v3_dtor_kinds *dtor_kind)
6065 {
6066   struct d_info di;
6067   struct demangle_component *dc;
6068   int ret;
6069
6070   *ctor_kind = (enum gnu_v3_ctor_kinds) 0;
6071   *dtor_kind = (enum gnu_v3_dtor_kinds) 0;
6072
6073   cplus_demangle_init_info (mangled, DMGL_GNU_V3, strlen (mangled), &di);
6074
6075   {
6076 #ifdef CP_DYNAMIC_ARRAYS
6077     __extension__ struct demangle_component comps[di.num_comps];
6078     __extension__ struct demangle_component *subs[di.num_subs];
6079
6080     di.comps = comps;
6081     di.subs = subs;
6082 #else
6083     di.comps = alloca (di.num_comps * sizeof (*di.comps));
6084     di.subs = alloca (di.num_subs * sizeof (*di.subs));
6085 #endif
6086
6087     dc = cplus_demangle_mangled_name (&di, 1);
6088
6089     /* Note that because we did not pass DMGL_PARAMS, we don't expect
6090        to demangle the entire string.  */
6091
6092     ret = 0;
6093     while (dc != NULL)
6094       {
6095         switch (dc->type)
6096           {
6097             /* These cannot appear on a constructor or destructor.  */
6098           case DEMANGLE_COMPONENT_RESTRICT_THIS:
6099           case DEMANGLE_COMPONENT_VOLATILE_THIS:
6100           case DEMANGLE_COMPONENT_CONST_THIS:
6101           case DEMANGLE_COMPONENT_REFERENCE_THIS:
6102           case DEMANGLE_COMPONENT_RVALUE_REFERENCE_THIS:
6103           default:
6104             dc = NULL;
6105             break;
6106           case DEMANGLE_COMPONENT_TYPED_NAME:
6107           case DEMANGLE_COMPONENT_TEMPLATE:
6108             dc = d_left (dc);
6109             break;
6110           case DEMANGLE_COMPONENT_QUAL_NAME:
6111           case DEMANGLE_COMPONENT_LOCAL_NAME:
6112             dc = d_right (dc);
6113             break;
6114           case DEMANGLE_COMPONENT_CTOR:
6115             *ctor_kind = dc->u.s_ctor.kind;
6116             ret = 1;
6117             dc = NULL;
6118             break;
6119           case DEMANGLE_COMPONENT_DTOR:
6120             *dtor_kind = dc->u.s_dtor.kind;
6121             ret = 1;
6122             dc = NULL;
6123             break;
6124           }
6125       }
6126   }
6127
6128   return ret;
6129 }
6130
6131 /* Return whether NAME is the mangled form of a g++ V3 ABI constructor
6132    name.  A non-zero return indicates the type of constructor.  */
6133
6134 enum gnu_v3_ctor_kinds
6135 is_gnu_v3_mangled_ctor (const char *name)
6136 {
6137   enum gnu_v3_ctor_kinds ctor_kind;
6138   enum gnu_v3_dtor_kinds dtor_kind;
6139
6140   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
6141     return (enum gnu_v3_ctor_kinds) 0;
6142   return ctor_kind;
6143 }
6144
6145
6146 /* Return whether NAME is the mangled form of a g++ V3 ABI destructor
6147    name.  A non-zero return indicates the type of destructor.  */
6148
6149 enum gnu_v3_dtor_kinds
6150 is_gnu_v3_mangled_dtor (const char *name)
6151 {
6152   enum gnu_v3_ctor_kinds ctor_kind;
6153   enum gnu_v3_dtor_kinds dtor_kind;
6154
6155   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
6156     return (enum gnu_v3_dtor_kinds) 0;
6157   return dtor_kind;
6158 }
6159
6160 #endif /* IN_GLIBCPP_V3 */
6161
6162 #ifdef STANDALONE_DEMANGLER
6163
6164 #include "getopt.h"
6165 #include "dyn-string.h"
6166
6167 static void print_usage (FILE* fp, int exit_value);
6168
6169 #define IS_ALPHA(CHAR)                                                  \
6170   (((CHAR) >= 'a' && (CHAR) <= 'z')                                     \
6171    || ((CHAR) >= 'A' && (CHAR) <= 'Z'))
6172
6173 /* Non-zero if CHAR is a character than can occur in a mangled name.  */
6174 #define is_mangled_char(CHAR)                                           \
6175   (IS_ALPHA (CHAR) || IS_DIGIT (CHAR)                                   \
6176    || (CHAR) == '_' || (CHAR) == '.' || (CHAR) == '$')
6177
6178 /* The name of this program, as invoked.  */
6179 const char* program_name;
6180
6181 /* Prints usage summary to FP and then exits with EXIT_VALUE.  */
6182
6183 static void
6184 print_usage (FILE* fp, int exit_value)
6185 {
6186   fprintf (fp, "Usage: %s [options] [names ...]\n", program_name);
6187   fprintf (fp, "Options:\n");
6188   fprintf (fp, "  -h,--help       Display this message.\n");
6189   fprintf (fp, "  -p,--no-params  Don't display function parameters\n");
6190   fprintf (fp, "  -v,--verbose    Produce verbose demanglings.\n");
6191   fprintf (fp, "If names are provided, they are demangled.  Otherwise filters standard input.\n");
6192
6193   exit (exit_value);
6194 }
6195
6196 /* Option specification for getopt_long.  */
6197 static const struct option long_options[] = 
6198 {
6199   { "help",      no_argument, NULL, 'h' },
6200   { "no-params", no_argument, NULL, 'p' },
6201   { "verbose",   no_argument, NULL, 'v' },
6202   { NULL,        no_argument, NULL, 0   },
6203 };
6204
6205 /* Main entry for a demangling filter executable.  It will demangle
6206    its command line arguments, if any.  If none are provided, it will
6207    filter stdin to stdout, replacing any recognized mangled C++ names
6208    with their demangled equivalents.  */
6209
6210 int
6211 main (int argc, char *argv[])
6212 {
6213   int i;
6214   int opt_char;
6215   int options = DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES;
6216
6217   /* Use the program name of this program, as invoked.  */
6218   program_name = argv[0];
6219
6220   /* Parse options.  */
6221   do 
6222     {
6223       opt_char = getopt_long (argc, argv, "hpv", long_options, NULL);
6224       switch (opt_char)
6225         {
6226         case '?':  /* Unrecognized option.  */
6227           print_usage (stderr, 1);
6228           break;
6229
6230         case 'h':
6231           print_usage (stdout, 0);
6232           break;
6233
6234         case 'p':
6235           options &= ~ DMGL_PARAMS;
6236           break;
6237
6238         case 'v':
6239           options |= DMGL_VERBOSE;
6240           break;
6241         }
6242     }
6243   while (opt_char != -1);
6244
6245   if (optind == argc) 
6246     /* No command line arguments were provided.  Filter stdin.  */
6247     {
6248       dyn_string_t mangled = dyn_string_new (3);
6249       char *s;
6250
6251       /* Read all of input.  */
6252       while (!feof (stdin))
6253         {
6254           char c;
6255
6256           /* Pile characters into mangled until we hit one that can't
6257              occur in a mangled name.  */
6258           c = getchar ();
6259           while (!feof (stdin) && is_mangled_char (c))
6260             {
6261               dyn_string_append_char (mangled, c);
6262               if (feof (stdin))
6263                 break;
6264               c = getchar ();
6265             }
6266
6267           if (dyn_string_length (mangled) > 0)
6268             {
6269 #ifdef IN_GLIBCPP_V3
6270               s = __cxa_demangle (dyn_string_buf (mangled), NULL, NULL, NULL);
6271 #else
6272               s = cplus_demangle_v3 (dyn_string_buf (mangled), options);
6273 #endif
6274
6275               if (s != NULL)
6276                 {
6277                   fputs (s, stdout);
6278                   free (s);
6279                 }
6280               else
6281                 {
6282                   /* It might not have been a mangled name.  Print the
6283                      original text.  */
6284                   fputs (dyn_string_buf (mangled), stdout);
6285                 }
6286
6287               dyn_string_clear (mangled);
6288             }
6289
6290           /* If we haven't hit EOF yet, we've read one character that
6291              can't occur in a mangled name, so print it out.  */
6292           if (!feof (stdin))
6293             putchar (c);
6294         }
6295
6296       dyn_string_delete (mangled);
6297     }
6298   else
6299     /* Demangle command line arguments.  */
6300     {
6301       /* Loop over command line arguments.  */
6302       for (i = optind; i < argc; ++i)
6303         {
6304           char *s;
6305 #ifdef IN_GLIBCPP_V3
6306           int status;
6307 #endif
6308
6309           /* Attempt to demangle.  */
6310 #ifdef IN_GLIBCPP_V3
6311           s = __cxa_demangle (argv[i], NULL, NULL, &status);
6312 #else
6313           s = cplus_demangle_v3 (argv[i], options);
6314 #endif
6315
6316           /* If it worked, print the demangled name.  */
6317           if (s != NULL)
6318             {
6319               printf ("%s\n", s);
6320               free (s);
6321             }
6322           else
6323             {
6324 #ifdef IN_GLIBCPP_V3
6325               fprintf (stderr, "Failed: %s (status %d)\n", argv[i], status);
6326 #else
6327               fprintf (stderr, "Failed: %s\n", argv[i]);
6328 #endif
6329             }
6330         }
6331     }
6332
6333   return 0;
6334 }
6335
6336 #endif /* STANDALONE_DEMANGLER */