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