OSDN Git Service

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