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