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