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