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