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