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