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