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