OSDN Git Service

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