OSDN Git Service

* cp-demangle.c (is_ctor_or_dtor): Fix error in last change.
[pf3gnuchains/gcc-fork.git] / libiberty / cp-demangle.c
1 /* Demangler for g++ V3 ABI.
2    Copyright (C) 2003 Free Software Foundation, Inc.
3    Written by Ian Lance Taylor <ian@wasabisystems.com>.
4
5    This file is part of the libiberty library, which is part of GCC.
6
7    This file is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    In addition to the permissions in the GNU General Public License, the
13    Free Software Foundation gives you unlimited permission to link the
14    compiled version of this file into combinations with other programs,
15    and to distribute those combinations without any restriction coming
16    from the use of this file.  (The General Public License restrictions
17    do apply in other respects; for example, they cover modification of
18    the file, and distribution when not linked into a combined
19    executable.)
20
21    This program is distributed in the hope that it will be useful,
22    but WITHOUT ANY WARRANTY; without even the implied warranty of
23    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24    GNU General Public License for more details.
25
26    You should have received a copy of the GNU General Public License
27    along with this program; if not, write to the Free Software
28    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
29 */
30
31 /* This code implements a demangler for the g++ V3 ABI.  The ABI is
32    described on this web page:
33        http://www.codesourcery.com/cxx-abi/abi.html#mangling
34
35    This code was written while looking at the demangler written by
36    Alex Samuel <samuel@codesourcery.com>.
37
38    This code first pulls the mangled name apart into a list of
39    components, and then walks the list generating the demangled
40    name.
41
42    This file will normally define the following functions, q.v.:
43       char *cplus_demangle_v3(const char *mangled, int options)
44       char *java_demangle_v3(const char *mangled)
45       enum gnu_v3_ctor_kinds is_gnu_v3_mangled_ctor (const char *name)
46       enum gnu_v3_dtor_kinds is_gnu_v3_mangled_dtor (const char *name)
47
48    Preprocessor macros you can define while compiling this file:
49
50    IN_LIBGCC2
51       If defined, this file defines the following function, q.v.:
52          char *__cxa_demangle (const char *mangled, char *buf, size_t *len,
53                                int *status)
54       instead of cplus_demangle_v3() and java_demangle_v3().
55
56    IN_GLIBCPP_V3
57       If defined, this file defines only __cxa_demangle().
58
59    STANDALONE_DEMANGLER
60       If defined, this file defines a main() function which demangles
61       any arguments, or, if none, demangles stdin.
62
63    CP_DEMANGLE_DEBUG
64       If defined, turns on debugging mode, which prints information on
65       stdout about the mangled string.  This is not generally useful.
66 */
67
68 #ifdef HAVE_CONFIG_H
69 #include "config.h"
70 #endif
71
72 #include <stdio.h>
73
74 #ifdef HAVE_STDLIB_H
75 #include <stdlib.h>
76 #endif
77 #ifdef HAVE_STRING_H
78 #include <string.h>
79 #endif
80
81 #include "ansidecl.h"
82 #include "libiberty.h"
83 #include "demangle.h"
84
85 /* See if the compiler supports dynamic arrays.  */
86
87 #ifdef __GNUC__
88 #define CP_DYNAMIC_ARRAYS
89 #else
90 #ifdef __STDC__
91 #ifdef __STDC_VERSION__
92 #if __STDC_VERSION__ >= 199901L
93 #define CP_DYNAMIC_ARRAYS
94 #endif /* __STDC__VERSION >= 199901L */
95 #endif /* defined (__STDC_VERSION__) */
96 #endif /* defined (__STDC__) */
97 #endif /* ! defined (__GNUC__) */
98
99 /* We avoid pulling in the ctype tables, to prevent pulling in
100    additional unresolved symbols when this code is used in a library.
101    FIXME: Is this really a valid reason?  This comes from the original
102    V3 demangler code.
103
104    As of this writing this file has the following undefined references
105    when compiled with -DIN_GLIBCPP_V3: malloc, realloc, free, memcpy,
106    strcpy, strcat, strlen.  */
107
108 #define IS_DIGIT(c) ((c) >= '0' && (c) <= '9')
109 #define IS_UPPER(c) ((c) >= 'A' && (c) <= 'Z')
110 #define IS_LOWER(c) ((c) >= 'a' && (c) <= 'z')
111
112 /* The prefix prepended by GCC to an identifier represnting the
113    anonymous namespace.  */
114 #define ANONYMOUS_NAMESPACE_PREFIX "_GLOBAL_"
115 #define ANONYMOUS_NAMESPACE_PREFIX_LEN \
116   (sizeof (ANONYMOUS_NAMESPACE_PREFIX) - 1)
117
118 /* Information we keep for operators.  */
119
120 struct d_operator_info
121 {
122   /* Mangled name.  */
123   const char *code;
124   /* Real name.  */
125   const char *name;
126   /* Length of real name.  */
127   int len;
128   /* Number of arguments.  */
129   int args;
130 };
131
132 /* How to print the value of a builtin type.  */
133
134 enum d_builtin_type_print
135 {
136   /* Print as (type)val.  */
137   D_PRINT_DEFAULT,
138   /* Print as integer.  */
139   D_PRINT_INT,
140   /* Print as long, with trailing `l'.  */
141   D_PRINT_LONG,
142   /* Print as bool.  */
143   D_PRINT_BOOL,
144   /* Print in usual way, but here to detect void.  */
145   D_PRINT_VOID
146 };
147
148 /* Information we keep for a builtin type.  */
149
150 struct d_builtin_type_info
151 {
152   /* Type name.  */
153   const char *name;
154   /* Length of type name.  */
155   int len;
156   /* Type name when using Java.  */
157   const char *java_name;
158   /* Length of java name.  */
159   int java_len;
160   /* How to print a value of this type.  */
161   enum d_builtin_type_print print;
162 };
163
164 /* Information we keep for the standard substitutions.  */
165
166 struct d_standard_sub_info
167 {
168   /* The code for this substitution.  */
169   char code;
170   /* The simple string it expands to.  */
171   const char *simple_expansion;
172   /* The length of the simple expansion.  */
173   int simple_len;
174   /* The results of a full, verbose, expansion.  This is used when
175      qualifying a constructor/destructor, or when in verbose mode.  */
176   const char *full_expansion;
177   /* The length of the full expansion.  */
178   int full_len;
179   /* What to set the last_name field of d_info to; NULL if we should
180      not set it.  This is only relevant when qualifying a
181      constructor/destructor.  */
182   const char *set_last_name;
183   /* The length of set_last_name.  */
184   int set_last_name_len;
185 };
186
187 /* Component types found in mangled names.  */
188
189 enum d_comp_type
190 {
191   /* A name.  */
192   D_COMP_NAME,
193   /* A qualified name.  */
194   D_COMP_QUAL_NAME,
195   /* A local name.  */
196   D_COMP_LOCAL_NAME,
197   /* A typed name.  */
198   D_COMP_TYPED_NAME,
199   /* A template.  */
200   D_COMP_TEMPLATE,
201   /* A template parameter.  */
202   D_COMP_TEMPLATE_PARAM,
203   /* A constructor.  */
204   D_COMP_CTOR,
205   /* A destructor.  */
206   D_COMP_DTOR,
207   /* A vtable.  */
208   D_COMP_VTABLE,
209   /* A VTT structure.  */
210   D_COMP_VTT,
211   /* A construction vtable.  */
212   D_COMP_CONSTRUCTION_VTABLE,
213   /* A typeinfo structure.  */
214   D_COMP_TYPEINFO,
215   /* A typeinfo name.  */
216   D_COMP_TYPEINFO_NAME,
217   /* A typeinfo function.  */
218   D_COMP_TYPEINFO_FN,
219   /* A thunk.  */
220   D_COMP_THUNK,
221   /* A virtual thunk.  */
222   D_COMP_VIRTUAL_THUNK,
223   /* A covariant thunk.  */
224   D_COMP_COVARIANT_THUNK,
225   /* A Java class.  */
226   D_COMP_JAVA_CLASS,
227   /* A guard variable.  */
228   D_COMP_GUARD,
229   /* A reference temporary.  */
230   D_COMP_REFTEMP,
231   /* A standard substitution.  */
232   D_COMP_SUB_STD,
233   /* The restrict qualifier.  */
234   D_COMP_RESTRICT,
235   /* The volatile qualifier.  */
236   D_COMP_VOLATILE,
237   /* The const qualifier.  */
238   D_COMP_CONST,
239   /* The restrict qualifier modifying a member function.  */
240   D_COMP_RESTRICT_THIS,
241   /* The volatile qualifier modifying a member function.  */
242   D_COMP_VOLATILE_THIS,
243   /* The const qualifier modifying a member function.  */
244   D_COMP_CONST_THIS,
245   /* A vendor qualifier.  */
246   D_COMP_VENDOR_TYPE_QUAL,
247   /* A pointer.  */
248   D_COMP_POINTER,
249   /* A reference.  */
250   D_COMP_REFERENCE,
251   /* A complex type.  */
252   D_COMP_COMPLEX,
253   /* An imaginary type.  */
254   D_COMP_IMAGINARY,
255   /* A builtin type.  */
256   D_COMP_BUILTIN_TYPE,
257   /* A vendor's builtin type.  */
258   D_COMP_VENDOR_TYPE,
259   /* A function type.  */
260   D_COMP_FUNCTION_TYPE,
261   /* An array type.  */
262   D_COMP_ARRAY_TYPE,
263   /* A pointer to member type.  */
264   D_COMP_PTRMEM_TYPE,
265   /* An argument list.  */
266   D_COMP_ARGLIST,
267   /* A template argument list.  */
268   D_COMP_TEMPLATE_ARGLIST,
269   /* An operator.  */
270   D_COMP_OPERATOR,
271   /* An extended operator.  */
272   D_COMP_EXTENDED_OPERATOR,
273   /* A typecast.  */
274   D_COMP_CAST,
275   /* A unary expression.  */
276   D_COMP_UNARY,
277   /* A binary expression.  */
278   D_COMP_BINARY,
279   /* Arguments to a binary expression.  */
280   D_COMP_BINARY_ARGS,
281   /* A trinary expression.  */
282   D_COMP_TRINARY,
283   /* Arguments to a trinary expression.  */
284   D_COMP_TRINARY_ARG1,
285   D_COMP_TRINARY_ARG2,
286   /* A literal.  */
287   D_COMP_LITERAL,
288   /* A negative literal.  */
289   D_COMP_LITERAL_NEG
290 };
291
292 /* A component of the mangled name.  */
293
294 struct d_comp
295 {
296   /* The type of this component.  */
297   enum d_comp_type type;
298   union
299   {
300     /* For D_COMP_NAME.  */
301     struct
302     {
303       /* A pointer to the name (not NULL terminated) and it's
304          length.  */
305       const char *s;
306       int len;
307     } s_name;
308
309     /* For D_COMP_OPERATOR.  */
310     struct
311     {
312       /* Operator.  */
313       const struct d_operator_info *op;
314     } s_operator;
315
316     /* For D_COMP_EXTENDED_OPERATOR.  */
317     struct
318     {
319       /* Number of arguments.  */
320       int args;
321       /* Name.  */
322       struct d_comp *name;
323     } s_extended_operator;
324
325     /* For D_COMP_CTOR.  */
326     struct
327     {
328       enum gnu_v3_ctor_kinds kind;
329       struct d_comp *name;
330     } s_ctor;
331
332     /* For D_COMP_DTOR.  */
333     struct
334     {
335       enum gnu_v3_dtor_kinds kind;
336       struct d_comp *name;
337     } s_dtor;
338
339     /* For D_COMP_BUILTIN_TYPE.  */
340     struct
341     {
342       const struct d_builtin_type_info *type;
343     } s_builtin;
344
345     /* For D_COMP_SUB_STD.  */
346     struct
347     {
348       const char* string;
349       int len;
350     } s_string;
351
352     /* For D_COMP_TEMPLATE_PARAM.  */
353     struct
354     {
355       long number;
356     } s_number;
357
358     /* For other types.  */
359     struct
360     {
361       struct d_comp *left;
362       struct d_comp *right;
363     } s_binary;
364
365   } u;
366 };
367
368 #define d_left(dc) ((dc)->u.s_binary.left)
369 #define d_right(dc) ((dc)->u.s_binary.right)
370
371 /* The information structure we pass around.  */
372
373 struct d_info
374 {
375   /* The string we are demangling.  */
376   const char *s;
377   /* The end of the string we are demangling.  */
378   const char *send;
379   /* The options passed to the demangler.  */
380   int options;
381   /* The next character in the string to consider.  */
382   const char *n;
383   /* The array of components.  */
384   struct d_comp *comps;
385   /* The index of the next available component.  */
386   int next_comp;
387   /* The number of available component structures.  */
388   int num_comps;
389   /* The array of substitutions.  */
390   struct d_comp **subs;
391   /* The index of the next substitution.  */
392   int next_sub;
393   /* The number of available entries in the subs array.  */
394   int num_subs;
395   /* The number of substitutions which we actually made from the subs
396      array, plus the number of template parameter references we
397      saw.  */
398   int did_subs;
399   /* The last name we saw, for constructors and destructors.  */
400   struct d_comp *last_name;
401   /* A running total of the length of large expansions from the
402      mangled name to the demangled name, such as standard
403      substitutions and builtin types.  */
404   int expansion;
405 };
406
407 #define d_peek_char(di) (*((di)->n))
408 #define d_peek_next_char(di) ((di)->n[1])
409 #define d_advance(di, i) ((di)->n += (i))
410 #define d_next_char(di) (*((di)->n++))
411 #define d_str(di) ((di)->n)
412
413 /* A list of templates.  This is used while printing.  */
414
415 struct d_print_template
416 {
417   /* Next template on the list.  */
418   struct d_print_template *next;
419   /* This template.  */
420   const struct d_comp *template;
421 };
422
423 /* A list of type modifiers.  This is used while printing.  */
424
425 struct d_print_mod
426 {
427   /* Next modifier on the list.  These are in the reverse of the order
428      in which they appeared in the mangled string.  */
429   struct d_print_mod *next;
430   /* The modifier.  */
431   const struct d_comp *mod;
432   /* Whether this modifier was printed.  */
433   int printed;
434   /* The list of templates which applies to this modifier.  */
435   struct d_print_template *templates;
436 };
437
438 /* We use this structure to hold information during printing.  */
439
440 struct d_print_info
441 {
442   /* The options passed to the demangler.  */
443   int options;
444   /* Buffer holding the result.  */
445   char *buf;
446   /* Current length of data in buffer.  */
447   size_t len;
448   /* Allocated size of buffer.  */
449   size_t alc;
450   /* The current list of templates, if any.  */
451   struct d_print_template *templates;
452   /* The current list of modifiers (e.g., pointer, reference, etc.),
453      if any.  */
454   struct d_print_mod *modifiers;
455   /* Set to 1 if we had a memory allocation failure.  */
456   int allocation_failure;
457 };
458
459 #define d_print_saw_error(dpi) ((dpi)->buf == NULL)
460
461 #define d_append_char(dpi, c) \
462   do \
463     { \
464       if ((dpi)->buf != NULL && (dpi)->len < (dpi)->alc) \
465         (dpi)->buf[(dpi)->len++] = (c); \
466       else \
467         d_print_append_char ((dpi), (c)); \
468     } \
469   while (0)
470
471 #define d_append_buffer(dpi, s, l) \
472   do \
473     { \
474       if ((dpi)->buf != NULL && (dpi)->len + (l) <= (dpi)->alc) \
475         { \
476           memcpy ((dpi)->buf + (dpi)->len, (s), (l)); \
477           (dpi)->len += l; \
478         } \
479       else \
480         d_print_append_buffer ((dpi), (s), (l)); \
481     } \
482   while (0)
483
484 #define d_append_string_constant(dpi, s) \
485   d_append_buffer (dpi, (s), sizeof (s) - 1)
486
487 #define d_last_char(dpi) \
488   ((dpi)->buf == NULL || (dpi)->len == 0 ? '\0' : (dpi)->buf[(dpi)->len - 1])
489
490 #ifdef CP_DEMANGLE_DEBUG
491 static void d_dump PARAMS ((struct d_comp *, int));
492 #endif
493 static struct d_comp *d_make_empty PARAMS ((struct d_info *,
494                                             enum d_comp_type));
495 static struct d_comp *d_make_comp PARAMS ((struct d_info *, enum d_comp_type,
496                                            struct d_comp *, struct d_comp *));
497 static struct d_comp *d_make_name PARAMS ((struct d_info *, const char *,
498                                            int));
499 static struct d_comp *d_make_builtin_type PARAMS ((struct d_info *,
500                                                    const struct d_builtin_type_info *));
501 static struct d_comp *d_make_operator PARAMS ((struct d_info *,
502                                                const struct d_operator_info *));
503 static struct d_comp *d_make_extended_operator PARAMS ((struct d_info *,
504                                                         int,
505                                                         struct d_comp *));
506 static struct d_comp *d_make_ctor PARAMS ((struct d_info *,
507                                            enum gnu_v3_ctor_kinds,
508                                            struct d_comp *));
509 static struct d_comp *d_make_dtor PARAMS ((struct d_info *,
510                                            enum gnu_v3_dtor_kinds,
511                                            struct d_comp *));
512 static struct d_comp *d_make_template_param PARAMS ((struct d_info *, long));
513 static struct d_comp *d_make_sub PARAMS ((struct d_info *, const char *, int));
514 static struct d_comp *d_mangled_name PARAMS ((struct d_info *, int));
515 static int has_return_type PARAMS ((struct d_comp *));
516 static int is_ctor_dtor_or_conversion PARAMS ((struct d_comp *));
517 static struct d_comp *d_encoding PARAMS ((struct d_info *, int));
518 static struct d_comp *d_name PARAMS ((struct d_info *));
519 static struct d_comp *d_nested_name PARAMS ((struct d_info *));
520 static struct d_comp *d_prefix PARAMS ((struct d_info *));
521 static struct d_comp *d_unqualified_name PARAMS ((struct d_info *));
522 static struct d_comp *d_source_name PARAMS ((struct d_info *));
523 static long d_number PARAMS ((struct d_info *));
524 static struct d_comp *d_identifier PARAMS ((struct d_info *, int));
525 static struct d_comp *d_operator_name PARAMS ((struct d_info *));
526 static struct d_comp *d_special_name PARAMS ((struct d_info *));
527 static int d_call_offset PARAMS ((struct d_info *, int));
528 static struct d_comp *d_ctor_dtor_name PARAMS ((struct d_info *));
529 static struct d_comp *d_type PARAMS ((struct d_info *));
530 static struct d_comp **d_cv_qualifiers PARAMS ((struct d_info *,
531                                                 struct d_comp **, int));
532 static struct d_comp *d_function_type PARAMS ((struct d_info *));
533 static struct d_comp *d_bare_function_type PARAMS ((struct d_info *, int));
534 static struct d_comp *d_class_enum_type PARAMS ((struct d_info *));
535 static struct d_comp *d_array_type PARAMS ((struct d_info *));
536 static struct d_comp *d_pointer_to_member_type PARAMS ((struct d_info *));
537 static struct d_comp *d_template_param PARAMS ((struct d_info *));
538 static struct d_comp *d_template_args PARAMS ((struct d_info *));
539 static struct d_comp *d_template_arg PARAMS ((struct d_info *));
540 static struct d_comp *d_expression PARAMS ((struct d_info *));
541 static struct d_comp *d_expr_primary PARAMS ((struct d_info *));
542 static struct d_comp *d_local_name PARAMS ((struct d_info *));
543 static int d_discriminator PARAMS ((struct d_info *));
544 static int d_add_substitution PARAMS ((struct d_info *, struct d_comp *));
545 static struct d_comp *d_substitution PARAMS ((struct d_info *, int));
546 static void d_print_resize PARAMS ((struct d_print_info *, size_t));
547 static void d_print_append_char PARAMS ((struct d_print_info *, int));
548 static void d_print_append_buffer PARAMS ((struct d_print_info *, const char *,
549                                            size_t));
550 static void d_print_error PARAMS ((struct d_print_info *));
551 static char *d_print PARAMS ((int, const struct d_comp *, int, size_t *));
552 static void d_print_comp PARAMS ((struct d_print_info *,
553                                   const struct d_comp *));
554 static void d_print_java_identifier PARAMS ((struct d_print_info *,
555                                              const char *, int));
556 static void d_print_mod_list PARAMS ((struct d_print_info *,
557                                       struct d_print_mod *, int));
558 static void d_print_mod PARAMS ((struct d_print_info *,
559                                  const struct d_comp *));
560 static void d_print_function_type PARAMS ((struct d_print_info *,
561                                            const struct d_comp *,
562                                            struct d_print_mod *));
563 static void d_print_array_type PARAMS ((struct d_print_info *,
564                                         const struct d_comp *,
565                                         struct d_print_mod *));
566 static void d_print_expr_op PARAMS ((struct d_print_info *,
567                                      const struct d_comp *));
568 static void d_print_cast PARAMS ((struct d_print_info *,
569                                   const struct d_comp *));
570 static void d_init_info PARAMS ((const char *, int, size_t, struct d_info *));
571 static char *d_demangle PARAMS ((const char *, int, size_t *));
572
573 #ifdef CP_DEMANGLE_DEBUG
574
575 static void
576 d_dump (dc, indent)
577      struct d_comp *dc;
578      int indent;
579 {
580   int i;
581
582   if (dc == NULL)
583     return;
584
585   for (i = 0; i < indent; ++i)
586     putchar (' ');
587
588   switch (dc->type)
589     {
590     case D_COMP_NAME:
591       printf ("name '%.*s'\n", dc->u.s_name.len, dc->u.s_name.s);
592       return;
593     case D_COMP_TEMPLATE_PARAM:
594       printf ("template parameter %ld\n", dc->u.s_number.number);
595       return;
596     case D_COMP_CTOR:
597       printf ("constructor %d\n", (int) dc->u.s_ctor.kind);
598       d_dump (dc->u.s_ctor.name, indent + 2);
599       return;
600     case D_COMP_DTOR:
601       printf ("destructor %d\n", (int) dc->u.s_dtor.kind);
602       d_dump (dc->u.s_dtor.name, indent + 2);
603       return;
604     case D_COMP_SUB_STD:
605       printf ("standard substitution %s\n", dc->u.s_string.string);
606       return;
607     case D_COMP_BUILTIN_TYPE:
608       printf ("builtin type %s\n", dc->u.s_builtin.type->name);
609       return;
610     case D_COMP_OPERATOR:
611       printf ("operator %s\n", dc->u.s_operator.op->name);
612       return;
613     case D_COMP_EXTENDED_OPERATOR:
614       printf ("extended operator with %d args\n",
615               dc->u.s_extended_operator.args);
616       d_dump (dc->u.s_extended_operator.name, indent + 2);
617       return;
618
619     case D_COMP_QUAL_NAME:
620       printf ("qualified name\n");
621       break;
622     case D_COMP_LOCAL_NAME:
623       printf ("local name\n");
624       break;
625     case D_COMP_TYPED_NAME:
626       printf ("typed name\n");
627       break;
628     case D_COMP_TEMPLATE:
629       printf ("template\n");
630       break;
631     case D_COMP_VTABLE:
632       printf ("vtable\n");
633       break;
634     case D_COMP_VTT:
635       printf ("VTT\n");
636       break;
637     case D_COMP_CONSTRUCTION_VTABLE:
638       printf ("construction vtable\n");
639       break;
640     case D_COMP_TYPEINFO:
641       printf ("typeinfo\n");
642       break;
643     case D_COMP_TYPEINFO_NAME:
644       printf ("typeinfo name\n");
645       break;
646     case D_COMP_TYPEINFO_FN:
647       printf ("typeinfo function\n");
648       break;
649     case D_COMP_THUNK:
650       printf ("thunk\n");
651       break;
652     case D_COMP_VIRTUAL_THUNK:
653       printf ("virtual thunk\n");
654       break;
655     case D_COMP_COVARIANT_THUNK:
656       printf ("covariant thunk\n");
657       break;
658     case D_COMP_JAVA_CLASS:
659       printf ("java class\n");
660       break;
661     case D_COMP_GUARD:
662       printf ("guard\n");
663       break;
664     case D_COMP_REFTEMP:
665       printf ("reference temporary\n");
666       break;
667     case D_COMP_RESTRICT:
668       printf ("restrict\n");
669       break;
670     case D_COMP_VOLATILE:
671       printf ("volatile\n");
672       break;
673     case D_COMP_CONST:
674       printf ("const\n");
675       break;
676     case D_COMP_RESTRICT_THIS:
677       printf ("restrict this\n");
678       break;
679     case D_COMP_VOLATILE_THIS:
680       printf ("volatile this\n");
681       break;
682     case D_COMP_CONST_THIS:
683       printf ("const this\n");
684       break;
685     case D_COMP_VENDOR_TYPE_QUAL:
686       printf ("vendor type qualifier\n");
687       break;
688     case D_COMP_POINTER:
689       printf ("pointer\n");
690       break;
691     case D_COMP_REFERENCE:
692       printf ("reference\n");
693       break;
694     case D_COMP_COMPLEX:
695       printf ("complex\n");
696       break;
697     case D_COMP_IMAGINARY:
698       printf ("imaginary\n");
699       break;
700     case D_COMP_VENDOR_TYPE:
701       printf ("vendor type\n");
702       break;
703     case D_COMP_FUNCTION_TYPE:
704       printf ("function type\n");
705       break;
706     case D_COMP_ARRAY_TYPE:
707       printf ("array type\n");
708       break;
709     case D_COMP_PTRMEM_TYPE:
710       printf ("pointer to member type\n");
711       break;
712     case D_COMP_ARGLIST:
713       printf ("argument list\n");
714       break;
715     case D_COMP_TEMPLATE_ARGLIST:
716       printf ("template argument list\n");
717       break;
718     case D_COMP_CAST:
719       printf ("cast\n");
720       break;
721     case D_COMP_UNARY:
722       printf ("unary operator\n");
723       break;
724     case D_COMP_BINARY:
725       printf ("binary operator\n");
726       break;
727     case D_COMP_BINARY_ARGS:
728       printf ("binary operator arguments\n");
729       break;
730     case D_COMP_TRINARY:
731       printf ("trinary operator\n");
732       break;
733     case D_COMP_TRINARY_ARG1:
734       printf ("trinary operator arguments 1\n");
735       break;
736     case D_COMP_TRINARY_ARG2:
737       printf ("trinary operator arguments 1\n");
738       break;
739     case D_COMP_LITERAL:
740       printf ("literal\n");
741       break;
742     case D_COMP_LITERAL_NEG:
743       printf ("negative literal\n");
744       break;
745     }
746
747   d_dump (d_left (dc), indent + 2);
748   d_dump (d_right (dc), indent + 2);
749 }
750
751 #endif /* CP_DEMANGLE_DEBUG */
752
753 /* Add a new component.  */
754
755 static struct d_comp *
756 d_make_empty (di, type)
757      struct d_info *di;
758      enum d_comp_type type;
759 {
760   struct d_comp *p;
761
762   if (di->next_comp >= di->num_comps)
763     return NULL;
764   p = &di->comps[di->next_comp];
765   p->type = type;
766   ++di->next_comp;
767   return p;
768 }
769
770 /* Add a new generic component.  */
771
772 static struct d_comp *
773 d_make_comp (di, type, left, right)
774      struct d_info *di;
775      enum d_comp_type type;
776      struct d_comp *left;
777      struct d_comp *right;
778 {
779   struct d_comp *p;
780
781   /* We check for errors here.  A typical error would be a NULL return
782      from a subroutine.  We catch those here, and return NULL
783      upward.  */
784   switch (type)
785     {
786       /* These types require two parameters.  */
787     case D_COMP_QUAL_NAME:
788     case D_COMP_LOCAL_NAME:
789     case D_COMP_TYPED_NAME:
790     case D_COMP_TEMPLATE:
791     case D_COMP_VENDOR_TYPE_QUAL:
792     case D_COMP_PTRMEM_TYPE:
793     case D_COMP_UNARY:
794     case D_COMP_BINARY:
795     case D_COMP_BINARY_ARGS:
796     case D_COMP_TRINARY:
797     case D_COMP_TRINARY_ARG1:
798     case D_COMP_TRINARY_ARG2:
799     case D_COMP_LITERAL:
800     case D_COMP_LITERAL_NEG:
801       if (left == NULL || right == NULL)
802         return NULL;
803       break;
804
805       /* These types only require one parameter.  */
806     case D_COMP_VTABLE:
807     case D_COMP_VTT:
808     case D_COMP_CONSTRUCTION_VTABLE:
809     case D_COMP_TYPEINFO:
810     case D_COMP_TYPEINFO_NAME:
811     case D_COMP_TYPEINFO_FN:
812     case D_COMP_THUNK:
813     case D_COMP_VIRTUAL_THUNK:
814     case D_COMP_COVARIANT_THUNK:
815     case D_COMP_JAVA_CLASS:
816     case D_COMP_GUARD:
817     case D_COMP_REFTEMP:
818     case D_COMP_POINTER:
819     case D_COMP_REFERENCE:
820     case D_COMP_COMPLEX:
821     case D_COMP_IMAGINARY:
822     case D_COMP_VENDOR_TYPE:
823     case D_COMP_ARGLIST:
824     case D_COMP_TEMPLATE_ARGLIST:
825     case D_COMP_CAST:
826       if (left == NULL)
827         return NULL;
828       break;
829
830       /* This needs a right parameter, but the left parameter can be
831          empty.  */
832     case D_COMP_ARRAY_TYPE:
833       if (right == NULL)
834         return NULL;
835       break;
836
837       /* These are allowed to have no parameters--in some cases they
838          will be filled in later.  */
839     case D_COMP_FUNCTION_TYPE:
840     case D_COMP_RESTRICT:
841     case D_COMP_VOLATILE:
842     case D_COMP_CONST:
843     case D_COMP_RESTRICT_THIS:
844     case D_COMP_VOLATILE_THIS:
845     case D_COMP_CONST_THIS:
846       break;
847
848       /* Other types should not be seen here.  */
849     default:
850       return NULL;
851     }
852
853   p = d_make_empty (di, type);
854   if (p != NULL)
855     {
856       p->u.s_binary.left = left;
857       p->u.s_binary.right = right;
858     }
859   return p;
860 }
861
862 /* Add a new name component.  */
863
864 static struct d_comp *
865 d_make_name (di, s, len)
866      struct d_info *di;
867      const char *s;
868      int len;
869 {
870   struct d_comp *p;
871
872   if (s == NULL || len == 0)
873     return NULL;
874   p = d_make_empty (di, D_COMP_NAME);
875   if (p != NULL)
876     {
877       p->u.s_name.s = s;
878       p->u.s_name.len = len;
879     }
880   return p;
881 }
882
883 /* Add a new builtin type component.  */
884
885 static struct d_comp *
886 d_make_builtin_type (di, type)
887      struct d_info *di;
888      const struct d_builtin_type_info *type;
889 {
890   struct d_comp *p;
891
892   if (type == NULL)
893     return NULL;
894   p = d_make_empty (di, D_COMP_BUILTIN_TYPE);
895   if (p != NULL)
896     p->u.s_builtin.type = type;
897   return p;
898 }
899
900 /* Add a new operator component.  */
901
902 static struct d_comp *
903 d_make_operator (di, op)
904      struct d_info *di;
905      const struct d_operator_info *op;
906 {
907   struct d_comp *p;
908
909   p = d_make_empty (di, D_COMP_OPERATOR);
910   if (p != NULL)
911     p->u.s_operator.op = op;
912   return p;
913 }
914
915 /* Add a new extended operator component.  */
916
917 static struct d_comp *
918 d_make_extended_operator (di, args, name)
919      struct d_info *di;
920      int args;
921      struct d_comp *name;
922 {
923   struct d_comp *p;
924
925   if (name == NULL)
926     return NULL;
927   p = d_make_empty (di, D_COMP_EXTENDED_OPERATOR);
928   if (p != NULL)
929     {
930       p->u.s_extended_operator.args = args;
931       p->u.s_extended_operator.name = name;
932     }
933   return p;
934 }
935
936 /* Add a new constructor component.  */
937
938 static struct d_comp *
939 d_make_ctor (di, kind,  name)
940      struct d_info *di;
941      enum gnu_v3_ctor_kinds kind;
942      struct d_comp *name;
943 {
944   struct d_comp *p;
945
946   if (name == NULL)
947     return NULL;
948   p = d_make_empty (di, D_COMP_CTOR);
949   if (p != NULL)
950     {
951       p->u.s_ctor.kind = kind;
952       p->u.s_ctor.name = name;
953     }
954   return p;
955 }
956
957 /* Add a new destructor component.  */
958
959 static struct d_comp *
960 d_make_dtor (di, kind, name)
961      struct d_info *di;
962      enum gnu_v3_dtor_kinds kind;
963      struct d_comp *name;
964 {
965   struct d_comp *p;
966
967   if (name == NULL)
968     return NULL;
969   p = d_make_empty (di, D_COMP_DTOR);
970   if (p != NULL)
971     {
972       p->u.s_dtor.kind = kind;
973       p->u.s_dtor.name = name;
974     }
975   return p;
976 }
977
978 /* Add a new template parameter.  */
979
980 static struct d_comp *
981 d_make_template_param (di, i)
982      struct d_info *di;
983      long i;
984 {
985   struct d_comp *p;
986
987   p = d_make_empty (di, D_COMP_TEMPLATE_PARAM);
988   if (p != NULL)
989     p->u.s_number.number = i;
990   return p;
991 }
992
993 /* Add a new standard substitution component.  */
994
995 static struct d_comp *
996 d_make_sub (di, name, len)
997      struct d_info *di;
998      const char *name;
999      int len;
1000 {
1001   struct d_comp *p;
1002
1003   p = d_make_empty (di, D_COMP_SUB_STD);
1004   if (p != NULL)
1005     {
1006       p->u.s_string.string = name;
1007       p->u.s_string.len = len;
1008     }
1009   return p;
1010 }
1011
1012 /* <mangled-name> ::= _Z <encoding>
1013
1014    TOP_LEVEL is non-zero when called at the top level.  */
1015
1016 static struct d_comp *
1017 d_mangled_name (di, top_level)
1018      struct d_info *di;
1019      int top_level;
1020 {
1021   if (d_next_char (di) != '_')
1022     return NULL;
1023   if (d_next_char (di) != 'Z')
1024     return NULL;
1025   return d_encoding (di, top_level);
1026 }
1027
1028 /* Return whether a function should have a return type.  The argument
1029    is the function name, which may be qualified in various ways.  The
1030    rules are that template functions have return types with some
1031    exceptions, function types which are not part of a function name
1032    mangling have return types with some exceptions, and non-template
1033    function names do not have return types.  The exceptions are that
1034    constructors, destructors, and conversion operators do not have
1035    return types.  */
1036
1037 static int
1038 has_return_type (dc)
1039      struct d_comp *dc;
1040 {
1041   if (dc == NULL)
1042     return 0;
1043   switch (dc->type)
1044     {
1045     default:
1046       return 0;
1047     case D_COMP_TEMPLATE:
1048       return ! is_ctor_dtor_or_conversion (d_left (dc));
1049     case D_COMP_RESTRICT_THIS:
1050     case D_COMP_VOLATILE_THIS:
1051     case D_COMP_CONST_THIS:
1052       return has_return_type (d_left (dc));
1053     }
1054 }
1055
1056 /* Return whether a name is a constructor, a destructor, or a
1057    conversion operator.  */
1058
1059 static int
1060 is_ctor_dtor_or_conversion (dc)
1061      struct d_comp *dc;
1062 {
1063   if (dc == NULL)
1064     return 0;
1065   switch (dc->type)
1066     {
1067     default:
1068       return 0;
1069     case D_COMP_QUAL_NAME:
1070     case D_COMP_LOCAL_NAME:
1071       return is_ctor_dtor_or_conversion (d_right (dc));
1072     case D_COMP_CTOR:
1073     case D_COMP_DTOR:
1074     case D_COMP_CAST:
1075       return 1;
1076     }
1077 }
1078
1079 /* <encoding> ::= <(function) name> <bare-function-type>
1080               ::= <(data) name>
1081               ::= <special-name>
1082
1083    TOP_LEVEL is non-zero when called at the top level, in which case
1084    if DMGL_PARAMS is not set we do not demangle the function
1085    parameters.  We only set this at the top level, because otherwise
1086    we would not correctly demangle names in local scopes.  */
1087
1088 static struct d_comp *
1089 d_encoding (di, top_level)
1090      struct d_info *di;
1091      int top_level;
1092 {
1093   char peek = d_peek_char (di);
1094
1095   if (peek == 'G' || peek == 'T')
1096     return d_special_name (di);
1097   else
1098     {
1099       struct d_comp *dc;
1100
1101       dc = d_name (di);
1102
1103       if (dc != NULL && top_level && (di->options & DMGL_PARAMS) == 0)
1104         {
1105           /* Strip off any initial CV-qualifiers, as they really apply
1106              to the `this' parameter, and they were not output by the
1107              v2 demangler without DMGL_PARAMS.  */
1108           while (dc->type == D_COMP_RESTRICT_THIS
1109                  || dc->type == D_COMP_VOLATILE_THIS
1110                  || dc->type == D_COMP_CONST_THIS)
1111             dc = d_left (dc);
1112           return dc;
1113         }
1114
1115       peek = d_peek_char (di);
1116       if (peek == '\0' || peek == 'E')
1117         return dc;
1118       return d_make_comp (di, D_COMP_TYPED_NAME, dc,
1119                           d_bare_function_type (di, has_return_type (dc)));
1120     }
1121 }
1122
1123 /* <name> ::= <nested-name>
1124           ::= <unscoped-name>
1125           ::= <unscoped-template-name> <template-args>
1126           ::= <local-name>
1127
1128    <unscoped-name> ::= <unqualified-name>
1129                    ::= St <unqualified-name>
1130
1131    <unscoped-template-name> ::= <unscoped-name>
1132                             ::= <substitution>
1133 */
1134
1135 static struct d_comp *
1136 d_name (di)
1137      struct d_info *di;
1138 {
1139   char peek = d_peek_char (di);
1140   struct d_comp *dc;
1141
1142   switch (peek)
1143     {
1144     case 'N':
1145       return d_nested_name (di);
1146
1147     case 'Z':
1148       return d_local_name (di);
1149
1150     case 'S':
1151       {
1152         int subst;
1153
1154         if (d_peek_next_char (di) != 't')
1155           {
1156             dc = d_substitution (di, 0);
1157             subst = 1;
1158           }
1159         else
1160           {
1161             d_advance (di, 2);
1162             dc = d_make_comp (di, D_COMP_QUAL_NAME, d_make_name (di, "std", 3),
1163                               d_unqualified_name (di));
1164             di->expansion += 3;
1165             subst = 0;
1166           }
1167
1168         if (d_peek_char (di) != 'I')
1169           {
1170             /* The grammar does not permit this case to occur if we
1171                called d_substitution() above (i.e., subst == 1).  We
1172                don't bother to check.  */
1173           }
1174         else
1175           {
1176             /* This is <template-args>, which means that we just saw
1177                <unscoped-template-name>, which is a substitution
1178                candidate if we didn't just get it from a
1179                substitution.  */
1180             if (! subst)
1181               {
1182                 if (! d_add_substitution (di, dc))
1183                   return NULL;
1184               }
1185             dc = d_make_comp (di, D_COMP_TEMPLATE, dc, d_template_args (di));
1186           }
1187
1188         return dc;
1189       }
1190
1191     default:
1192       dc = d_unqualified_name (di);
1193       if (d_peek_char (di) == 'I')
1194         {
1195           /* This is <template-args>, which means that we just saw
1196              <unscoped-template-name>, which is a substitution
1197              candidate.  */
1198           if (! d_add_substitution (di, dc))
1199             return NULL;
1200           dc = d_make_comp (di, D_COMP_TEMPLATE, dc, d_template_args (di));
1201         }
1202       return dc;
1203     }
1204 }
1205
1206 /* <nested-name> ::= N [<CV-qualifiers>] <prefix> <unqualified-name> E
1207                  ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1208 */
1209
1210 static struct d_comp *
1211 d_nested_name (di)
1212      struct d_info *di;
1213 {
1214   struct d_comp *ret;
1215   struct d_comp **pret;
1216
1217   if (d_next_char (di) != 'N')
1218     return NULL;
1219
1220   pret = d_cv_qualifiers (di, &ret, 1);
1221   if (pret == NULL)
1222     return NULL;
1223
1224   *pret = d_prefix (di);
1225   if (*pret == NULL)
1226     return NULL;
1227
1228   if (d_next_char (di) != 'E')
1229     return NULL;
1230
1231   return ret;
1232 }
1233
1234 /* <prefix> ::= <prefix> <unqualified-name>
1235             ::= <template-prefix> <template-args>
1236             ::= <template-param>
1237             ::=
1238             ::= <substitution>
1239
1240    <template-prefix> ::= <prefix> <(template) unqualified-name>
1241                      ::= <template-param>
1242                      ::= <substitution>
1243 */
1244
1245 static struct d_comp *
1246 d_prefix (di)
1247      struct d_info *di;
1248 {
1249   struct d_comp *ret = NULL;
1250
1251   while (1)
1252     {
1253       char peek;
1254       enum d_comp_type comb_type;
1255       struct d_comp *dc;
1256
1257       peek = d_peek_char (di);
1258       if (peek == '\0')
1259         return NULL;
1260
1261       /* The older code accepts a <local-name> here, but I don't see
1262          that in the grammar.  The older code does not accept a
1263          <template-param> here.  */
1264
1265       comb_type = D_COMP_QUAL_NAME;
1266       if (IS_DIGIT (peek)
1267           || IS_LOWER (peek)
1268           || peek == 'C'
1269           || peek == 'D')
1270         dc = d_unqualified_name (di);
1271       else if (peek == 'S')
1272         dc = d_substitution (di, 1);
1273       else if (peek == 'I')
1274         {
1275           if (ret == NULL)
1276             return NULL;
1277           comb_type = D_COMP_TEMPLATE;
1278           dc = d_template_args (di);
1279         }
1280       else if (peek == 'T')
1281         dc = d_template_param (di);
1282       else if (peek == 'E')
1283         return ret;
1284       else
1285         return NULL;
1286
1287       if (ret == NULL)
1288         ret = dc;
1289       else
1290         ret = d_make_comp (di, comb_type, ret, dc);
1291
1292       if (peek != 'S' && d_peek_char (di) != 'E')
1293         {
1294           if (! d_add_substitution (di, ret))
1295             return NULL;
1296         }
1297     }
1298 }
1299
1300 /* <unqualified-name> ::= <operator-name>
1301                       ::= <ctor-dtor-name>
1302                       ::= <source-name>
1303 */
1304
1305 static struct d_comp *
1306 d_unqualified_name (di)
1307      struct d_info *di;
1308 {
1309   char peek;
1310
1311   peek = d_peek_char (di);
1312   if (IS_DIGIT (peek))
1313     return d_source_name (di);
1314   else if (IS_LOWER (peek))
1315     {
1316       struct d_comp *ret;
1317
1318       ret = d_operator_name (di);
1319       if (ret != NULL && ret->type == D_COMP_OPERATOR)
1320         di->expansion += sizeof "operator" + ret->u.s_operator.op->len - 2;
1321       return ret;
1322     }
1323   else if (peek == 'C' || peek == 'D')
1324     return d_ctor_dtor_name (di);
1325   else
1326     return NULL;
1327 }
1328
1329 /* <source-name> ::= <(positive length) number> <identifier>  */
1330
1331 static struct d_comp *
1332 d_source_name (di)
1333      struct d_info *di;
1334 {
1335   long len;
1336   struct d_comp *ret;
1337
1338   len = d_number (di);
1339   if (len <= 0)
1340     return NULL;
1341   ret = d_identifier (di, len);
1342   di->last_name = ret;
1343   return ret;
1344 }
1345
1346 /* number ::= [n] <(non-negative decimal integer)>  */
1347
1348 static long
1349 d_number (di)
1350      struct d_info *di;
1351 {
1352   int negative;
1353   char peek;
1354   long ret;
1355
1356   negative = 0;
1357   peek = d_peek_char (di);
1358   if (peek == 'n')
1359     {
1360       negative = 1;
1361       d_advance (di, 1);
1362       peek = d_peek_char (di);
1363     }
1364
1365   ret = 0;
1366   while (1)
1367     {
1368       if (! IS_DIGIT (peek))
1369         {
1370           if (negative)
1371             ret = - ret;
1372           return ret;
1373         }
1374       ret = ret * 10 + peek - '0';
1375       d_advance (di, 1);
1376       peek = d_peek_char (di);
1377     }
1378 }
1379
1380 /* identifier ::= <(unqualified source code identifier)>  */
1381
1382 static struct d_comp *
1383 d_identifier (di, len)
1384      struct d_info *di;
1385      int len;
1386 {
1387   const char *name;
1388
1389   name = d_str (di);
1390
1391   if (di->send - name < len)
1392     return NULL;
1393
1394   d_advance (di, len);
1395
1396   /* A Java mangled name may have a trailing '$' if it is a C++
1397      keyword.  This '$' is not included in the length count.  We just
1398      ignore the '$'.  */
1399   if ((di->options & DMGL_JAVA) != 0
1400       && d_peek_char (di) == '$')
1401     d_advance (di, 1);
1402
1403   /* Look for something which looks like a gcc encoding of an
1404      anonymous namespace, and replace it with a more user friendly
1405      name.  */
1406   if (len >= (int) ANONYMOUS_NAMESPACE_PREFIX_LEN + 2
1407       && memcmp (name, ANONYMOUS_NAMESPACE_PREFIX,
1408                  ANONYMOUS_NAMESPACE_PREFIX_LEN) == 0)
1409     {
1410       const char *s;
1411
1412       s = name + ANONYMOUS_NAMESPACE_PREFIX_LEN;
1413       if ((*s == '.' || *s == '_' || *s == '$')
1414           && s[1] == 'N')
1415         {
1416           di->expansion -= len - sizeof "(anonymous namespace)";
1417           return d_make_name (di, "(anonymous namespace)",
1418                               sizeof "(anonymous namespace)" - 1);
1419         }
1420     }
1421
1422   return d_make_name (di, name, len);
1423 }
1424
1425 /* operator_name ::= many different two character encodings.
1426                  ::= cv <type>
1427                  ::= v <digit> <source-name>
1428 */
1429
1430 #define NL(s) s, (sizeof s) - 1
1431
1432 static const struct d_operator_info d_operators[] =
1433 {
1434   { "aN", NL ("&="),        2 },
1435   { "aS", NL ("="),         2 },
1436   { "aa", NL ("&&"),        2 },
1437   { "ad", NL ("&"),         1 },
1438   { "an", NL ("&"),         2 },
1439   { "cl", NL ("()"),        0 },
1440   { "cm", NL (","),         2 },
1441   { "co", NL ("~"),         1 },
1442   { "dV", NL ("/="),        2 },
1443   { "da", NL ("delete[]"),  1 },
1444   { "de", NL ("*"),         1 },
1445   { "dl", NL ("delete"),    1 },
1446   { "dv", NL ("/"),         2 },
1447   { "eO", NL ("^="),        2 },
1448   { "eo", NL ("^"),         2 },
1449   { "eq", NL ("=="),        2 },
1450   { "ge", NL (">="),        2 },
1451   { "gt", NL (">"),         2 },
1452   { "ix", NL ("[]"),        2 },
1453   { "lS", NL ("<<="),       2 },
1454   { "le", NL ("<="),        2 },
1455   { "ls", NL ("<<"),        2 },
1456   { "lt", NL ("<"),         2 },
1457   { "mI", NL ("-="),        2 },
1458   { "mL", NL ("*="),        2 },
1459   { "mi", NL ("-"),         2 },
1460   { "ml", NL ("*"),         2 },
1461   { "mm", NL ("--"),        1 },
1462   { "na", NL ("new[]"),     1 },
1463   { "ne", NL ("!="),        2 },
1464   { "ng", NL ("-"),         1 },
1465   { "nt", NL ("!"),         1 },
1466   { "nw", NL ("new"),       1 },
1467   { "oR", NL ("|="),        2 },
1468   { "oo", NL ("||"),        2 },
1469   { "or", NL ("|"),         2 },
1470   { "pL", NL ("+="),        2 },
1471   { "pl", NL ("+"),         2 },
1472   { "pm", NL ("->*"),       2 },
1473   { "pp", NL ("++"),        1 },
1474   { "ps", NL ("+"),         1 },
1475   { "pt", NL ("->"),        2 },
1476   { "qu", NL ("?"),         3 },
1477   { "rM", NL ("%="),        2 },
1478   { "rS", NL (">>="),       2 },
1479   { "rm", NL ("%"),         2 },
1480   { "rs", NL (">>"),        2 },
1481   { "st", NL ("sizeof "),   1 },
1482   { "sz", NL ("sizeof "),   1 }
1483 };
1484
1485 static struct d_comp *
1486 d_operator_name (di)
1487      struct d_info *di;
1488 {
1489   char c1;
1490   char c2;
1491
1492   c1 = d_next_char (di);
1493   c2 = d_next_char (di);
1494   if (c1 == 'v' && IS_DIGIT (c2))
1495     return d_make_extended_operator (di, c2 - '0', d_source_name (di));
1496   else if (c1 == 'c' && c2 == 'v')
1497     return d_make_comp (di, D_COMP_CAST, d_type (di), NULL);
1498   else
1499     {
1500       int low = 0;
1501       int high = sizeof (d_operators) / sizeof (d_operators[0]);
1502
1503       while (1)
1504         {
1505           int i;
1506           const struct d_operator_info *p;
1507
1508           i = low + (high - low) / 2;
1509           p = d_operators + i;
1510
1511           if (c1 == p->code[0] && c2 == p->code[1])
1512             return d_make_operator (di, p);
1513
1514           if (c1 < p->code[0] || (c1 == p->code[0] && c2 < p->code[1]))
1515             high = i;
1516           else
1517             low = i + 1;
1518           if (low == high)
1519             return NULL;
1520         }
1521     }
1522 }
1523
1524 /* <special-name> ::= TV <type>
1525                   ::= TT <type>
1526                   ::= TI <type>
1527                   ::= TS <type>
1528                   ::= GV <(object) name>
1529                   ::= T <call-offset> <(base) encoding>
1530                   ::= Tc <call-offset> <call-offset> <(base) encoding>
1531    Also g++ extensions:
1532                   ::= TC <type> <(offset) number> _ <(base) type>
1533                   ::= TF <type>
1534                   ::= TJ <type>
1535                   ::= GR <name>
1536 */
1537
1538 static struct d_comp *
1539 d_special_name (di)
1540      struct d_info *di;
1541 {
1542   char c;
1543
1544   di->expansion += 20;
1545   c = d_next_char (di);
1546   if (c == 'T')
1547     {
1548       switch (d_next_char (di))
1549         {
1550         case 'V':
1551           di->expansion -= 5;
1552           return d_make_comp (di, D_COMP_VTABLE, d_type (di), NULL);
1553         case 'T':
1554           di->expansion -= 10;
1555           return d_make_comp (di, D_COMP_VTT, d_type (di), NULL);
1556         case 'I':
1557           return d_make_comp (di, D_COMP_TYPEINFO, d_type (di), NULL);
1558         case 'S':
1559           return d_make_comp (di, D_COMP_TYPEINFO_NAME, d_type (di), NULL);
1560
1561         case 'h':
1562           if (! d_call_offset (di, 'h'))
1563             return NULL;
1564           return d_make_comp (di, D_COMP_THUNK, d_encoding (di, 0), NULL);
1565
1566         case 'v':
1567           if (! d_call_offset (di, 'v'))
1568             return NULL;
1569           return d_make_comp (di, D_COMP_VIRTUAL_THUNK, d_encoding (di, 0),
1570                               NULL);
1571
1572         case 'c':
1573           if (! d_call_offset (di, '\0'))
1574             return NULL;
1575           if (! d_call_offset (di, '\0'))
1576             return NULL;
1577           return d_make_comp (di, D_COMP_COVARIANT_THUNK, d_encoding (di, 0),
1578                               NULL);
1579
1580         case 'C':
1581           {
1582             struct d_comp *derived_type;
1583             long offset;
1584             struct d_comp *base_type;
1585
1586             derived_type = d_type (di);
1587             offset = d_number (di);
1588             if (offset < 0)
1589               return NULL;
1590             if (d_next_char (di) != '_')
1591               return NULL;
1592             base_type = d_type (di);
1593             /* We don't display the offset.  FIXME: We should display
1594                it in verbose mode.  */
1595             di->expansion += 5;
1596             return d_make_comp (di, D_COMP_CONSTRUCTION_VTABLE, base_type,
1597                                 derived_type);
1598           }
1599
1600         case 'F':
1601           return d_make_comp (di, D_COMP_TYPEINFO_FN, d_type (di), NULL);
1602         case 'J':
1603           return d_make_comp (di, D_COMP_JAVA_CLASS, d_type (di), NULL);
1604
1605         default:
1606           return NULL;
1607         }
1608     }
1609   else if (c == 'G')
1610     {
1611       switch (d_next_char (di))
1612         {
1613         case 'V':
1614           return d_make_comp (di, D_COMP_GUARD, d_name (di), NULL);
1615
1616         case 'R':
1617           return d_make_comp (di, D_COMP_REFTEMP, d_name (di), NULL);
1618
1619         default:
1620           return NULL;
1621         }
1622     }
1623   else
1624     return NULL;
1625 }
1626
1627 /* <call-offset> ::= h <nv-offset> _
1628                  ::= v <v-offset> _
1629
1630    <nv-offset> ::= <(offset) number>
1631
1632    <v-offset> ::= <(offset) number> _ <(virtual offset) number>
1633
1634    The C parameter, if not '\0', is a character we just read which is
1635    the start of the <call-offset>.
1636
1637    We don't display the offset information anywhere.  FIXME: We should
1638    display it in verbose mode.  */
1639
1640 static int
1641 d_call_offset (di, c)
1642      struct d_info *di;
1643      int c;
1644 {
1645   long offset;
1646   long virtual_offset;
1647
1648   if (c == '\0')
1649     c = d_next_char (di);
1650
1651   if (c == 'h')
1652     offset = d_number (di);
1653   else if (c == 'v')
1654     {
1655       offset = d_number (di);
1656       if (d_next_char (di) != '_')
1657         return 0;
1658       virtual_offset = d_number (di);
1659     }
1660   else
1661     return 0;
1662
1663   if (d_next_char (di) != '_')
1664     return 0;
1665
1666   return 1;
1667 }
1668
1669 /* <ctor-dtor-name> ::= C1
1670                     ::= C2
1671                     ::= C3
1672                     ::= D0
1673                     ::= D1
1674                     ::= D2
1675 */
1676
1677 static struct d_comp *
1678 d_ctor_dtor_name (di)
1679      struct d_info *di;
1680 {
1681   if (di->last_name != NULL)
1682     {
1683       if (di->last_name->type == D_COMP_NAME)
1684         di->expansion += di->last_name->u.s_name.len;
1685       else if (di->last_name->type == D_COMP_SUB_STD)
1686         di->expansion += di->last_name->u.s_string.len;
1687     }
1688   switch (d_next_char (di))
1689     {
1690     case 'C':
1691       {
1692         enum gnu_v3_ctor_kinds kind;
1693
1694         switch (d_next_char (di))
1695           {
1696           case '1':
1697             kind = gnu_v3_complete_object_ctor;
1698             break;
1699           case '2':
1700             kind = gnu_v3_base_object_ctor;
1701             break;
1702           case '3':
1703             kind = gnu_v3_complete_object_allocating_ctor;
1704             break;
1705           default:
1706             return NULL;
1707           }
1708         return d_make_ctor (di, kind, di->last_name);
1709       }
1710
1711     case 'D':
1712       {
1713         enum gnu_v3_dtor_kinds kind;
1714
1715         switch (d_next_char (di))
1716           {
1717           case '0':
1718             kind = gnu_v3_deleting_dtor;
1719             break;
1720           case '1':
1721             kind = gnu_v3_complete_object_dtor;
1722             break;
1723           case '2':
1724             kind = gnu_v3_base_object_dtor;
1725             break;
1726           default:
1727             return NULL;
1728           }
1729         return d_make_dtor (di, kind, di->last_name);
1730       }
1731
1732     default:
1733       return NULL;
1734     }
1735 }
1736
1737 /* <type> ::= <builtin-type>
1738           ::= <function-type>
1739           ::= <class-enum-type>
1740           ::= <array-type>
1741           ::= <pointer-to-member-type>
1742           ::= <template-param>
1743           ::= <template-template-param> <template-args>
1744           ::= <substitution>
1745           ::= <CV-qualifiers> <type>
1746           ::= P <type>
1747           ::= R <type>
1748           ::= C <type>
1749           ::= G <type>
1750           ::= U <source-name> <type>
1751
1752    <builtin-type> ::= various one letter codes
1753                   ::= u <source-name>
1754 */
1755
1756 static const struct d_builtin_type_info d_builtin_types[26] =
1757 {
1758   /* a */ { NL ("signed char"), NL ("signed char"),     D_PRINT_INT },
1759   /* b */ { NL ("bool"),        NL ("boolean"),         D_PRINT_BOOL },
1760   /* c */ { NL ("char"),        NL ("byte"),            D_PRINT_INT },
1761   /* d */ { NL ("double"),      NL ("double"),          D_PRINT_DEFAULT },
1762   /* e */ { NL ("long double"), NL ("long double"),     D_PRINT_DEFAULT },
1763   /* f */ { NL ("float"),       NL ("float"),           D_PRINT_DEFAULT },
1764   /* g */ { NL ("__float128"),  NL ("__float128"),      D_PRINT_DEFAULT },
1765   /* h */ { NL ("unsigned char"), NL ("unsigned char"), D_PRINT_INT },
1766   /* i */ { NL ("int"),         NL ("int"),             D_PRINT_INT },
1767   /* j */ { NL ("unsigned int"), NL ("unsigned"),       D_PRINT_INT },
1768   /* k */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1769   /* l */ { NL ("long"),        NL ("long"),            D_PRINT_LONG },
1770   /* m */ { NL ("unsigned long"), NL ("unsigned long"), D_PRINT_LONG },
1771   /* n */ { NL ("__int128"),    NL ("__int128"),        D_PRINT_DEFAULT },
1772   /* o */ { NL ("unsigned __int128"), NL ("unsigned __int128"), D_PRINT_DEFAULT },
1773   /* p */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1774   /* q */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1775   /* r */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1776   /* s */ { NL ("short"),       NL ("short"),           D_PRINT_INT },
1777   /* t */ { NL ("unsigned short"), NL ("unsigned short"), D_PRINT_INT },
1778   /* u */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1779   /* v */ { NL ("void"),        NL ("void"),            D_PRINT_VOID },
1780   /* w */ { NL ("wchar_t"),     NL ("char"),            D_PRINT_INT },
1781   /* x */ { NL ("long long"),   NL ("long"),            D_PRINT_DEFAULT },
1782   /* y */ { NL ("unsigned long long"), NL ("unsigned long long"), D_PRINT_DEFAULT },
1783   /* z */ { NL ("..."),         NL ("..."),             D_PRINT_DEFAULT },
1784 };
1785
1786 static struct d_comp *
1787 d_type (di)
1788      struct d_info *di;
1789 {
1790   char peek;
1791   struct d_comp *ret;
1792   int can_subst;
1793
1794   /* The ABI specifies that when CV-qualifiers are used, the base type
1795      is substitutable, and the fully qualified type is substitutable,
1796      but the base type with a strict subset of the CV-qualifiers is
1797      not substitutable.  The natural recursive implementation of the
1798      CV-qualifiers would cause subsets to be substitutable, so instead
1799      we pull them all off now.
1800
1801      FIXME: The ABI says that order-insensitive vendor qualifiers
1802      should be handled in the same way, but we have no way to tell
1803      which vendor qualifiers are order-insensitive and which are
1804      order-sensitive.  So we just assume that they are all
1805      order-sensitive.  g++ 3.4 supports only one vendor qualifier,
1806      __vector, and it treats it as order-sensitive when mangling
1807      names.  */
1808
1809   peek = d_peek_char (di);
1810   if (peek == 'r' || peek == 'V' || peek == 'K')
1811     {
1812       struct d_comp **pret;
1813
1814       pret = d_cv_qualifiers (di, &ret, 0);
1815       if (pret == NULL)
1816         return NULL;
1817       *pret = d_type (di);
1818       if (! d_add_substitution (di, ret))
1819         return NULL;
1820       return ret;
1821     }
1822
1823   can_subst = 1;
1824
1825   switch (peek)
1826     {
1827     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1828     case 'h': case 'i': case 'j':           case 'l': case 'm': case 'n':
1829     case 'o':                               case 's': case 't':
1830     case 'v': case 'w': case 'x': case 'y': case 'z':
1831       ret = d_make_builtin_type (di, &d_builtin_types[peek - 'a']);
1832       di->expansion += ret->u.s_builtin.type->len;
1833       can_subst = 0;
1834       d_advance (di, 1);
1835       break;
1836
1837     case 'u':
1838       d_advance (di, 1);
1839       ret = d_make_comp (di, D_COMP_VENDOR_TYPE, d_source_name (di), NULL);
1840       break;
1841
1842     case 'F':
1843       ret = d_function_type (di);
1844       break;
1845
1846     case '0': case '1': case '2': case '3': case '4':
1847     case '5': case '6': case '7': case '8': case '9':
1848     case 'N':
1849     case 'Z':
1850       ret = d_class_enum_type (di);
1851       break;
1852
1853     case 'A':
1854       ret = d_array_type (di);
1855       break;
1856
1857     case 'M':
1858       ret = d_pointer_to_member_type (di);
1859       break;
1860
1861     case 'T':
1862       ret = d_template_param (di);
1863       if (d_peek_char (di) == 'I')
1864         {
1865           /* This is <template-template-param> <template-args>.  The
1866              <template-template-param> part is a substitution
1867              candidate.  */
1868           if (! d_add_substitution (di, ret))
1869             return NULL;
1870           ret = d_make_comp (di, D_COMP_TEMPLATE, ret, d_template_args (di));
1871         }
1872       break;
1873
1874     case 'S':
1875       /* If this is a special substitution, then it is the start of
1876          <class-enum-type>.  */
1877       {
1878         char peek_next;
1879
1880         peek_next = d_peek_next_char (di);
1881         if (IS_DIGIT (peek_next)
1882             || peek_next == '_'
1883             || IS_UPPER (peek_next))
1884           {
1885             ret = d_substitution (di, 0);
1886             /* The substituted name may have been a template name and
1887                may be followed by tepmlate args.  */
1888             if (d_peek_char (di) == 'I')
1889               ret = d_make_comp (di, D_COMP_TEMPLATE, ret,
1890                                  d_template_args (di));
1891             else
1892               can_subst = 0;
1893           }
1894         else
1895           {
1896             ret = d_class_enum_type (di);
1897             /* If the substitution was a complete type, then it is not
1898                a new substitution candidate.  However, if the
1899                substitution was followed by template arguments, then
1900                the whole thing is a substitution candidate.  */
1901             if (ret != NULL && ret->type == D_COMP_SUB_STD)
1902               can_subst = 0;
1903           }
1904       }
1905       break;
1906
1907     case 'P':
1908       d_advance (di, 1);
1909       ret = d_make_comp (di, D_COMP_POINTER, d_type (di), NULL);
1910       break;
1911
1912     case 'R':
1913       d_advance (di, 1);
1914       ret = d_make_comp (di, D_COMP_REFERENCE, d_type (di), NULL);
1915       break;
1916
1917     case 'C':
1918       d_advance (di, 1);
1919       ret = d_make_comp (di, D_COMP_COMPLEX, d_type (di), NULL);
1920       break;
1921
1922     case 'G':
1923       d_advance (di, 1);
1924       ret = d_make_comp (di, D_COMP_IMAGINARY, d_type (di), NULL);
1925       break;
1926
1927     case 'U':
1928       d_advance (di, 1);
1929       ret = d_source_name (di);
1930       ret = d_make_comp (di, D_COMP_VENDOR_TYPE_QUAL, d_type (di), ret);
1931       break;
1932
1933     default:
1934       return NULL;
1935     }
1936
1937   if (can_subst)
1938     {
1939       if (! d_add_substitution (di, ret))
1940         return NULL;
1941     }
1942
1943   return ret;
1944 }
1945
1946 /* <CV-qualifiers> ::= [r] [V] [K]  */
1947
1948 static struct d_comp **
1949 d_cv_qualifiers (di, pret, member_fn)
1950      struct d_info *di;
1951      struct d_comp **pret;
1952      int member_fn;
1953 {
1954   char peek;
1955
1956   peek = d_peek_char (di);
1957   while (peek == 'r' || peek == 'V' || peek == 'K')
1958     {
1959       enum d_comp_type t;
1960
1961       d_advance (di, 1);
1962       if (peek == 'r')
1963         {
1964           t = member_fn ? D_COMP_RESTRICT_THIS : D_COMP_RESTRICT;
1965           di->expansion += sizeof "restrict";
1966         }
1967       else if (peek == 'V')
1968         {
1969           t = member_fn ? D_COMP_VOLATILE_THIS : D_COMP_VOLATILE;
1970           di->expansion += sizeof "volatile";
1971         }
1972       else
1973         {
1974           t = member_fn ? D_COMP_CONST_THIS : D_COMP_CONST;
1975           di->expansion += sizeof "const";
1976         }
1977
1978       *pret = d_make_comp (di, t, NULL, NULL);
1979       if (*pret == NULL)
1980         return NULL;
1981       pret = &d_left (*pret);
1982
1983       peek = d_peek_char (di);
1984     }
1985
1986   return pret;
1987 }
1988
1989 /* <function-type> ::= F [Y] <bare-function-type> E  */
1990
1991 static struct d_comp *
1992 d_function_type (di)
1993      struct d_info *di;
1994 {
1995   struct d_comp *ret;
1996
1997   if (d_next_char (di) != 'F')
1998     return NULL;
1999   if (d_peek_char (di) == 'Y')
2000     {
2001       /* Function has C linkage.  We don't print this information.
2002          FIXME: We should print it in verbose mode.  */
2003       d_advance (di, 1);
2004     }
2005   ret = d_bare_function_type (di, 1);
2006   if (d_next_char (di) != 'E')
2007     return NULL;
2008   return ret;
2009 }
2010
2011 /* <bare-function-type> ::= <type>+  */
2012
2013 static struct d_comp *
2014 d_bare_function_type (di, has_return_type)
2015      struct d_info *di;
2016      int has_return_type;
2017 {
2018   struct d_comp *return_type;
2019   struct d_comp *tl;
2020   struct d_comp **ptl;
2021
2022   return_type = NULL;
2023   tl = NULL;
2024   ptl = &tl;
2025   while (1)
2026     {
2027       char peek;
2028       struct d_comp *type;
2029
2030       peek = d_peek_char (di);
2031       if (peek == '\0' || peek == 'E')
2032         break;
2033       type = d_type (di);
2034       if (type == NULL)
2035         return NULL;
2036       if (has_return_type)
2037         {
2038           return_type = type;
2039           has_return_type = 0;
2040         }
2041       else
2042         {
2043           *ptl = d_make_comp (di, D_COMP_ARGLIST, type, NULL);
2044           if (*ptl == NULL)
2045             return NULL;
2046           ptl = &d_right (*ptl);
2047         }
2048     }
2049
2050   /* There should be at least one parameter type besides the optional
2051      return type.  A function which takes no arguments will have a
2052      single parameter type void.  */
2053   if (tl == NULL)
2054     return NULL;
2055
2056   /* If we have a single parameter type void, omit it.  */
2057   if (d_right (tl) == NULL
2058       && d_left (tl)->type == D_COMP_BUILTIN_TYPE
2059       && d_left (tl)->u.s_builtin.type->print == D_PRINT_VOID)
2060     {
2061       di->expansion -= d_left (tl)->u.s_builtin.type->len;
2062       tl = NULL;
2063     }
2064
2065   return d_make_comp (di, D_COMP_FUNCTION_TYPE, return_type, tl);
2066 }
2067
2068 /* <class-enum-type> ::= <name>  */
2069
2070 static struct d_comp *
2071 d_class_enum_type (di)
2072      struct d_info *di;
2073 {
2074   return d_name (di);
2075 }
2076
2077 /* <array-type> ::= A <(positive dimension) number> _ <(element) type>
2078                 ::= A [<(dimension) expression>] _ <(element) type>
2079 */
2080
2081 static struct d_comp *
2082 d_array_type (di)
2083      struct d_info *di;
2084 {
2085   char peek;
2086   struct d_comp *dim;
2087
2088   if (d_next_char (di) != 'A')
2089     return NULL;
2090
2091   peek = d_peek_char (di);
2092   if (peek == '_')
2093     dim = NULL;
2094   else if (IS_DIGIT (peek))
2095     {
2096       const char *s;
2097
2098       s = d_str (di);
2099       do
2100         {
2101           d_advance (di, 1);
2102           peek = d_peek_char (di);
2103         }
2104       while (IS_DIGIT (peek));
2105       dim = d_make_name (di, s, d_str (di) - s);
2106       if (dim == NULL)
2107         return NULL;
2108     }
2109   else
2110     {
2111       dim = d_expression (di);
2112       if (dim == NULL)
2113         return NULL;
2114     }
2115
2116   if (d_next_char (di) != '_')
2117     return NULL;
2118
2119   return d_make_comp (di, D_COMP_ARRAY_TYPE, dim, d_type (di));
2120 }
2121
2122 /* <pointer-to-member-type> ::= M <(class) type> <(member) type>  */
2123
2124 static struct d_comp *
2125 d_pointer_to_member_type (di)
2126      struct d_info *di;
2127 {
2128   struct d_comp *cl;
2129   struct d_comp *mem;
2130   struct d_comp **pmem;
2131
2132   if (d_next_char (di) != 'M')
2133     return NULL;
2134
2135   cl = d_type (di);
2136
2137   /* The ABI specifies that any type can be a substitution source, and
2138      that M is followed by two types, and that when a CV-qualified
2139      type is seen both the base type and the CV-qualified types are
2140      substitution sources.  The ABI also specifies that for a pointer
2141      to a CV-qualified member function, the qualifiers are attached to
2142      the second type.  Given the grammar, a plain reading of the ABI
2143      suggests that both the CV-qualified member function and the
2144      non-qualified member function are substitution sources.  However,
2145      g++ does not work that way.  g++ treats only the CV-qualified
2146      member function as a substitution source.  FIXME.  So to work
2147      with g++, we need to pull off the CV-qualifiers here, in order to
2148      avoid calling add_substitution() in d_type().  */
2149
2150   pmem = d_cv_qualifiers (di, &mem, 1);
2151   if (pmem == NULL)
2152     return NULL;
2153   *pmem = d_type (di);
2154
2155   return d_make_comp (di, D_COMP_PTRMEM_TYPE, cl, mem);
2156 }
2157
2158 /* <template-param> ::= T_
2159                     ::= T <(parameter-2 non-negative) number> _
2160 */
2161
2162 static struct d_comp *
2163 d_template_param (di)
2164      struct d_info *di;
2165 {
2166   long param;
2167
2168   if (d_next_char (di) != 'T')
2169     return NULL;
2170
2171   if (d_peek_char (di) == '_')
2172     param = 0;
2173   else
2174     {
2175       param = d_number (di);
2176       if (param < 0)
2177         return NULL;
2178       param += 1;
2179     }
2180
2181   if (d_next_char (di) != '_')
2182     return NULL;
2183
2184   ++di->did_subs;
2185
2186   return d_make_template_param (di, param);
2187 }
2188
2189 /* <template-args> ::= I <template-arg>+ E  */
2190
2191 static struct d_comp *
2192 d_template_args (di)
2193      struct d_info *di;
2194 {
2195   struct d_comp *hold_last_name;
2196   struct d_comp *al;
2197   struct d_comp **pal;
2198
2199   /* Preserve the last name we saw--don't let the template arguments
2200      clobber it, as that would give us the wrong name for a subsequent
2201      constructor or destructor.  */
2202   hold_last_name = di->last_name;
2203
2204   if (d_next_char (di) != 'I')
2205     return NULL;
2206
2207   al = NULL;
2208   pal = &al;
2209   while (1)
2210     {
2211       struct d_comp *a;
2212
2213       a = d_template_arg (di);
2214       if (a == NULL)
2215         return NULL;
2216
2217       *pal = d_make_comp (di, D_COMP_TEMPLATE_ARGLIST, a, NULL);
2218       if (*pal == NULL)
2219         return NULL;
2220       pal = &d_right (*pal);
2221
2222       if (d_peek_char (di) == 'E')
2223         {
2224           d_advance (di, 1);
2225           break;
2226         }
2227     }
2228
2229   di->last_name = hold_last_name;
2230
2231   return al;
2232 }
2233
2234 /* <template-arg> ::= <type>
2235                   ::= X <expression> E
2236                   ::= <expr-primary>
2237 */
2238
2239 static struct d_comp *
2240 d_template_arg (di)
2241      struct d_info *di;
2242 {
2243   struct d_comp *ret;
2244
2245   switch (d_peek_char (di))
2246     {
2247     case 'X':
2248       d_advance (di, 1);
2249       ret = d_expression (di);
2250       if (d_next_char (di) != 'E')
2251         return NULL;
2252       return ret;
2253
2254     case 'L':
2255       return d_expr_primary (di);
2256
2257     default:
2258       return d_type (di);
2259     }
2260 }
2261
2262 /* <expression> ::= <(unary) operator-name> <expression>
2263                 ::= <(binary) operator-name> <expression> <expression>
2264                 ::= <(trinary) operator-name> <expression> <expression> <expression>
2265                 ::= st <type>
2266                 ::= <template-param>
2267                 ::= sr <type> <unqualified-name>
2268                 ::= sr <type> <unqualified-name> <template-args>
2269                 ::= <expr-primary>
2270 */
2271
2272 static struct d_comp *
2273 d_expression (di)
2274      struct d_info *di;
2275 {
2276   char peek;
2277
2278   peek = d_peek_char (di);
2279   if (peek == 'L')
2280     return d_expr_primary (di);
2281   else if (peek == 'T')
2282     return d_template_param (di);
2283   else if (peek == 's' && d_peek_next_char (di) == 'r')
2284     {
2285       struct d_comp *type;
2286       struct d_comp *name;
2287
2288       d_advance (di, 2);
2289       type = d_type (di);
2290       name = d_unqualified_name (di);
2291       if (d_peek_char (di) != 'I')
2292         return d_make_comp (di, D_COMP_QUAL_NAME, type, name);
2293       else
2294         return d_make_comp (di, D_COMP_QUAL_NAME, type,
2295                             d_make_comp (di, D_COMP_TEMPLATE, name,
2296                                          d_template_args (di)));
2297     }
2298   else
2299     {
2300       struct d_comp *op;
2301       int args;
2302
2303       op = d_operator_name (di);
2304       if (op == NULL)
2305         return NULL;
2306
2307       if (op->type == D_COMP_OPERATOR)
2308         di->expansion += op->u.s_operator.op->len - 2;
2309
2310       if (op->type == D_COMP_OPERATOR
2311           && strcmp (op->u.s_operator.op->code, "st") == 0)
2312         return d_make_comp (di, D_COMP_UNARY, op, d_type (di));
2313
2314       switch (op->type)
2315         {
2316         default:
2317           return NULL;
2318         case D_COMP_OPERATOR:
2319           args = op->u.s_operator.op->args;
2320           break;
2321         case D_COMP_EXTENDED_OPERATOR:
2322           args = op->u.s_extended_operator.args;
2323           break;
2324         case D_COMP_CAST:
2325           args = 1;
2326           break;
2327         }
2328
2329       switch (args)
2330         {
2331         case 1:
2332           return d_make_comp (di, D_COMP_UNARY, op, d_expression (di));
2333         case 2:
2334           {
2335             struct d_comp *left;
2336
2337             left = d_expression (di);
2338             return d_make_comp (di, D_COMP_BINARY, op,
2339                                 d_make_comp (di, D_COMP_BINARY_ARGS, left,
2340                                              d_expression (di)));
2341           }
2342         case 3:
2343           {
2344             struct d_comp *first;
2345             struct d_comp *second;
2346
2347             first = d_expression (di);
2348             second = d_expression (di);
2349             return d_make_comp (di, D_COMP_TRINARY, op,
2350                                 d_make_comp (di, D_COMP_TRINARY_ARG1, first,
2351                                              d_make_comp (di,
2352                                                           D_COMP_TRINARY_ARG2,
2353                                                           second,
2354                                                           d_expression (di))));
2355           }
2356         default:
2357           return NULL;
2358         }
2359     }
2360 }
2361
2362 /* <expr-primary> ::= L <type> <(value) number> E
2363                   ::= L <type> <(value) float> E
2364                   ::= L <mangled-name> E
2365 */
2366
2367 static struct d_comp *
2368 d_expr_primary (di)
2369      struct d_info *di;
2370 {
2371   struct d_comp *ret;
2372
2373   if (d_next_char (di) != 'L')
2374     return NULL;
2375   if (d_peek_char (di) == '_')
2376     ret = d_mangled_name (di, 0);
2377   else
2378     {
2379       struct d_comp *type;
2380       enum d_comp_type t;
2381       const char *s;
2382
2383       type = d_type (di);
2384
2385       /* If we have a type we know how to print, we aren't going to
2386          print the type name itself.  */
2387       if (type->type == D_COMP_BUILTIN_TYPE
2388           && type->u.s_builtin.type->print != D_PRINT_DEFAULT)
2389         di->expansion -= type->u.s_builtin.type->len;
2390
2391       /* Rather than try to interpret the literal value, we just
2392          collect it as a string.  Note that it's possible to have a
2393          floating point literal here.  The ABI specifies that the
2394          format of such literals is machine independent.  That's fine,
2395          but what's not fine is that versions of g++ up to 3.2 with
2396          -fabi-version=1 used upper case letters in the hex constant,
2397          and dumped out gcc's internal representation.  That makes it
2398          hard to tell where the constant ends, and hard to dump the
2399          constant in any readable form anyhow.  We don't attempt to
2400          handle these cases.  */
2401
2402       t = D_COMP_LITERAL;
2403       if (d_peek_char (di) == 'n')
2404         {
2405           t = D_COMP_LITERAL_NEG;
2406           d_advance (di, 1);
2407         }
2408       s = d_str (di);
2409       while (d_peek_char (di) != 'E')
2410         d_advance (di, 1);
2411       ret = d_make_comp (di, t, type, d_make_name (di, s, d_str (di) - s));
2412     }
2413   if (d_next_char (di) != 'E')
2414     return NULL;
2415   return ret;
2416 }
2417
2418 /* <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
2419                 ::= Z <(function) encoding> E s [<discriminator>]
2420 */
2421
2422 static struct d_comp *
2423 d_local_name (di)
2424      struct d_info *di;
2425 {
2426   struct d_comp *function;
2427
2428   if (d_next_char (di) != 'Z')
2429     return NULL;
2430
2431   function = d_encoding (di, 0);
2432
2433   if (d_next_char (di) != 'E')
2434     return NULL;
2435
2436   if (d_peek_char (di) == 's')
2437     {
2438       d_advance (di, 1);
2439       if (! d_discriminator (di))
2440         return NULL;
2441       return d_make_comp (di, D_COMP_LOCAL_NAME, function,
2442                           d_make_name (di, "string literal",
2443                                        sizeof "string literal" - 1));
2444     }
2445   else
2446     {
2447       struct d_comp *name;
2448
2449       name = d_name (di);
2450       if (! d_discriminator (di))
2451         return NULL;
2452       return d_make_comp (di, D_COMP_LOCAL_NAME, function, name);
2453     }
2454 }
2455
2456 /* <discriminator> ::= _ <(non-negative) number>
2457
2458    We demangle the discriminator, but we don't print it out.  FIXME:
2459    We should print it out in verbose mode.  */
2460
2461 static int
2462 d_discriminator (di)
2463      struct d_info *di;
2464 {
2465   long discrim;
2466
2467   if (d_peek_char (di) != '_')
2468     return 1;
2469   d_advance (di, 1);
2470   discrim = d_number (di);
2471   if (discrim < 0)
2472     return 0;
2473   return 1;
2474 }
2475
2476 /* Add a new substitution.  */
2477
2478 static int
2479 d_add_substitution (di, dc)
2480      struct d_info *di;
2481      struct d_comp *dc;
2482 {
2483   if (dc == NULL)
2484     return 0;
2485   if (di->next_sub >= di->num_subs)
2486     return 0;
2487   di->subs[di->next_sub] = dc;
2488   ++di->next_sub;
2489   return 1;
2490 }
2491
2492 /* <substitution> ::= S <seq-id> _
2493                   ::= S_
2494                   ::= St
2495                   ::= Sa
2496                   ::= Sb
2497                   ::= Ss
2498                   ::= Si
2499                   ::= So
2500                   ::= Sd
2501
2502    If PREFIX is non-zero, then this type is being used as a prefix in
2503    a qualified name.  In this case, for the standard substitutions, we
2504    need to check whether we are being used as a prefix for a
2505    constructor or destructor, and return a full template name.
2506    Otherwise we will get something like std::iostream::~iostream()
2507    which does not correspond particularly well to any function which
2508    actually appears in the source.
2509 */
2510
2511 static const struct d_standard_sub_info standard_subs[] =
2512 {
2513   { 't', NL ("std"),
2514     NL ("std"),
2515     NULL, 0 },
2516   { 'a', NL ("std::allocator"),
2517     NL ("std::allocator"),
2518     NL ("allocator") },
2519   { 'b', NL ("std::basic_string"),
2520     NL ("std::basic_string"),
2521     NL ("basic_string") },
2522   { 's', NL ("std::string"),
2523     NL ("std::basic_string<char, std::char_traits<char>, std::allocator<char> >"),
2524     NL ("basic_string") },
2525   { 'i', NL ("std::istream"),
2526     NL ("std::basic_istream<char, std::char_traits<char> >"),
2527     NL ("basic_istream") },
2528   { 'o', NL ("std::ostream"),
2529     NL ("std::basic_ostream<char, std::char_traits<char> >"),
2530     NL ("basic_ostream") },
2531   { 'd', NL ("std::iostream"),
2532     NL ("std::basic_iostream<char, std::char_traits<char> >"),
2533     NL ("basic_iostream") }
2534 };
2535
2536 static struct d_comp *
2537 d_substitution (di, prefix)
2538      struct d_info *di;
2539      int prefix;
2540 {
2541   char c;
2542
2543   if (d_next_char (di) != 'S')
2544     return NULL;
2545
2546   c = d_next_char (di);
2547   if (c == '_' || IS_DIGIT (c) || IS_UPPER (c))
2548     {
2549       int id;
2550
2551       id = 0;
2552       if (c != '_')
2553         {
2554           do
2555             {
2556               if (IS_DIGIT (c))
2557                 id = id * 36 + c - '0';
2558               else if (IS_UPPER (c))
2559                 id = id * 36 + c - 'A' + 10;
2560               else
2561                 return NULL;
2562               c = d_next_char (di);
2563             }
2564           while (c != '_');
2565
2566           ++id;
2567         }
2568
2569       if (id >= di->next_sub)
2570         return NULL;
2571
2572       ++di->did_subs;
2573
2574       return di->subs[id];
2575     }
2576   else
2577     {
2578       int verbose;
2579       const struct d_standard_sub_info *p;
2580       const struct d_standard_sub_info *pend;
2581
2582       verbose = (di->options & DMGL_VERBOSE) != 0;
2583       if (! verbose && prefix)
2584         {
2585           char peek;
2586
2587           peek = d_peek_char (di);
2588           if (peek == 'C' || peek == 'D')
2589             verbose = 1;
2590         }
2591
2592       pend = (&standard_subs[0]
2593               + sizeof standard_subs / sizeof standard_subs[0]);
2594       for (p = &standard_subs[0]; p < pend; ++p)
2595         {
2596           if (c == p->code)
2597             {
2598               const char *s;
2599               int len;
2600
2601               if (p->set_last_name != NULL)
2602                 di->last_name = d_make_sub (di, p->set_last_name,
2603                                             p->set_last_name_len);
2604               if (verbose)
2605                 {
2606                   s = p->full_expansion;
2607                   len = p->full_len;
2608                 }
2609               else
2610                 {
2611                   s = p->simple_expansion;
2612                   len = p->simple_len;
2613                 }
2614               di->expansion += len;
2615               return d_make_sub (di, s, len);
2616             }
2617         }
2618
2619       return NULL;
2620     }
2621 }
2622
2623 /* Resize the print buffer.  */
2624
2625 static void
2626 d_print_resize (dpi, add)
2627      struct d_print_info *dpi;
2628      size_t add;
2629 {
2630   size_t need;
2631
2632   if (dpi->buf == NULL)
2633     return;
2634   need = dpi->len + add;
2635   while (need > dpi->alc)
2636     {
2637       size_t newalc;
2638       char *newbuf;
2639
2640       newalc = dpi->alc * 2;
2641       newbuf = realloc (dpi->buf, newalc);
2642       if (newbuf == NULL)
2643         {
2644           free (dpi->buf);
2645           dpi->buf = NULL;
2646           dpi->allocation_failure = 1;
2647           return;
2648         }
2649       dpi->buf = newbuf;
2650       dpi->alc = newalc;
2651     }
2652 }
2653
2654 /* Append a character to the print buffer.  */
2655
2656 static void
2657 d_print_append_char (dpi, c)
2658      struct d_print_info *dpi;
2659      int c;
2660 {
2661   if (dpi->buf != NULL)
2662     {
2663       if (dpi->len >= dpi->alc)
2664         {
2665           d_print_resize (dpi, 1);
2666           if (dpi->buf == NULL)
2667             return;
2668         }
2669
2670       dpi->buf[dpi->len] = c;
2671       ++dpi->len;
2672     }
2673 }
2674
2675 /* Append a buffer to the print buffer.  */
2676
2677 static void
2678 d_print_append_buffer (dpi, s, l)
2679      struct d_print_info *dpi;
2680      const char *s;
2681      size_t l;
2682 {
2683   if (dpi->buf != NULL)
2684     {
2685       if (dpi->len + l > dpi->alc)
2686         {
2687           d_print_resize (dpi, l);
2688           if (dpi->buf == NULL)
2689             return;
2690         }
2691
2692       memcpy (dpi->buf + dpi->len, s, l);
2693       dpi->len += l;
2694     }
2695 }
2696
2697 /* Indicate that an error occurred during printing.  */
2698
2699 static void
2700 d_print_error (dpi)
2701      struct d_print_info *dpi;
2702 {
2703   free (dpi->buf);
2704   dpi->buf = NULL;
2705 }
2706
2707 /* Turn components into a human readable string.  OPTIONS is the
2708    options bits passed to the demangler.  DC is the tree to print.
2709    ESTIMATE is a guess at the length of the result.  This returns a
2710    string allocated by malloc, or NULL on error.  On success, this
2711    sets *PALC to the size of the allocated buffer.  On failure, this
2712    sets *PALC to 0 for a bad parse, or to 1 for a memory allocation
2713    failure.  */
2714
2715 static char *
2716 d_print (options, dc, estimate, palc)
2717      int options;
2718      const struct d_comp *dc;
2719      int estimate;
2720      size_t *palc;
2721 {
2722   struct d_print_info dpi;
2723
2724   dpi.options = options;
2725
2726   dpi.alc = estimate + 1;
2727   dpi.buf = malloc (dpi.alc);
2728   if (dpi.buf == NULL)
2729     {
2730       *palc = 1;
2731       return NULL;
2732     }
2733
2734   dpi.len = 0;
2735   dpi.templates = NULL;
2736   dpi.modifiers = NULL;
2737
2738   dpi.allocation_failure = 0;
2739
2740   d_print_comp (&dpi, dc);
2741
2742   d_append_char (&dpi, '\0');
2743
2744   if (dpi.buf != NULL)
2745     *palc = dpi.alc;
2746   else
2747     *palc = dpi.allocation_failure;
2748
2749   return dpi.buf;
2750 }
2751
2752 /* Subroutine to handle components.  */
2753
2754 static void
2755 d_print_comp (dpi, dc)
2756      struct d_print_info *dpi;
2757      const struct d_comp *dc;
2758 {
2759   if (dc == NULL)
2760     {
2761       d_print_error (dpi);
2762       return;
2763     }
2764   if (d_print_saw_error (dpi))
2765     return;
2766
2767   switch (dc->type)
2768     {
2769     case D_COMP_NAME:
2770       if ((dpi->options & DMGL_JAVA) == 0)
2771         d_append_buffer (dpi, dc->u.s_name.s, dc->u.s_name.len);
2772       else
2773         d_print_java_identifier (dpi, dc->u.s_name.s, dc->u.s_name.len);
2774       return;
2775
2776     case D_COMP_QUAL_NAME:
2777     case D_COMP_LOCAL_NAME:
2778       d_print_comp (dpi, d_left (dc));
2779       if ((dpi->options & DMGL_JAVA) == 0)
2780         d_append_string_constant (dpi, "::");
2781       else
2782         d_append_char (dpi, '.');
2783       d_print_comp (dpi, d_right (dc));
2784       return;
2785
2786     case D_COMP_TYPED_NAME:
2787       {
2788         struct d_print_mod *hold_modifiers;
2789         struct d_comp *typed_name;
2790         struct d_print_mod adpm[4];
2791         unsigned int i;
2792         struct d_print_template dpt;
2793
2794         /* Pass the name down to the type so that it can be printed in
2795            the right place for the type.  We also have to pass down
2796            any CV-qualifiers, which apply to the this parameter.  */
2797         hold_modifiers = dpi->modifiers;
2798         i = 0;
2799         typed_name = d_left (dc);
2800         while (typed_name != NULL)
2801           {
2802             if (i >= sizeof adpm / sizeof adpm[0])
2803               {
2804                 d_print_error (dpi);
2805                 return;
2806               }
2807
2808             adpm[i].next = dpi->modifiers;
2809             dpi->modifiers = &adpm[i];
2810             adpm[i].mod = typed_name;
2811             adpm[i].printed = 0;
2812             adpm[i].templates = dpi->templates;
2813             ++i;
2814
2815             if (typed_name->type != D_COMP_RESTRICT_THIS
2816                 && typed_name->type != D_COMP_VOLATILE_THIS
2817                 && typed_name->type != D_COMP_CONST_THIS)
2818               break;
2819
2820             typed_name = d_left (typed_name);
2821           }
2822
2823         /* If typed_name is a template, then it applies to the
2824            function type as well.  */
2825         if (typed_name->type == D_COMP_TEMPLATE)
2826           {
2827             dpt.next = dpi->templates;
2828             dpi->templates = &dpt;
2829             dpt.template = typed_name;
2830           }
2831
2832         /* If typed_name is a D_COMP_LOCAL_NAME, then there may be
2833            CV-qualifiers on its right argument which really apply
2834            here; this happens when parsing a class which is local to a
2835            function.  */
2836         if (typed_name->type == D_COMP_LOCAL_NAME)
2837           {
2838             struct d_comp *local_name;
2839
2840             local_name = d_right (typed_name);
2841             while (local_name->type == D_COMP_RESTRICT_THIS
2842                    || local_name->type == D_COMP_VOLATILE_THIS
2843                    || local_name->type == D_COMP_CONST_THIS)
2844               {
2845                 if (i >= sizeof adpm / sizeof adpm[0])
2846                   {
2847                     d_print_error (dpi);
2848                     return;
2849                   }
2850
2851                 adpm[i] = adpm[i - 1];
2852                 adpm[i].next = &adpm[i - 1];
2853                 dpi->modifiers = &adpm[i];
2854
2855                 adpm[i - 1].mod = local_name;
2856                 adpm[i - 1].printed = 0;
2857                 adpm[i - 1].templates = dpi->templates;
2858                 ++i;
2859
2860                 local_name = d_left (local_name);
2861               }
2862           }
2863
2864         d_print_comp (dpi, d_right (dc));
2865
2866         if (typed_name->type == D_COMP_TEMPLATE)
2867           dpi->templates = dpt.next;
2868
2869         /* If the modifiers didn't get printed by the type, print them
2870            now.  */
2871         while (i > 0)
2872           {
2873             --i;
2874             if (! adpm[i].printed)
2875               {
2876                 d_append_char (dpi, ' ');
2877                 d_print_mod (dpi, adpm[i].mod);
2878               }
2879           }
2880
2881         dpi->modifiers = hold_modifiers;
2882
2883         return;
2884       }
2885
2886     case D_COMP_TEMPLATE:
2887       {
2888         struct d_print_mod *hold_dpm;
2889
2890         /* Don't push modifiers into a template definition.  Doing so
2891            could give the wrong definition for a template argument.
2892            Instead, treat the template essentially as a name.  */
2893
2894         hold_dpm = dpi->modifiers;
2895         dpi->modifiers = NULL;
2896
2897         d_print_comp (dpi, d_left (dc));
2898         if (d_last_char (dpi) == '<')
2899           d_append_char (dpi, ' ');
2900         d_append_char (dpi, '<');
2901         d_print_comp (dpi, d_right (dc));
2902         /* Avoid generating two consecutive '>' characters, to avoid
2903            the C++ syntactic ambiguity.  */
2904         if (d_last_char (dpi) == '>')
2905           d_append_char (dpi, ' ');
2906         d_append_char (dpi, '>');
2907
2908         dpi->modifiers = hold_dpm;
2909
2910         return;
2911       }
2912
2913     case D_COMP_TEMPLATE_PARAM:
2914       {
2915         long i;
2916         struct d_comp *a;
2917         struct d_print_template *hold_dpt;
2918
2919         if (dpi->templates == NULL)
2920           {
2921             d_print_error (dpi);
2922             return;
2923           }
2924         i = dc->u.s_number.number;
2925         for (a = d_right (dpi->templates->template);
2926              a != NULL;
2927              a = d_right (a))
2928           {
2929             if (a->type != D_COMP_TEMPLATE_ARGLIST)
2930               {
2931                 d_print_error (dpi);
2932                 return;
2933               }
2934             if (i <= 0)
2935               break;
2936             --i;
2937           }
2938         if (i != 0 || a == NULL)
2939           {
2940             d_print_error (dpi);
2941             return;
2942           }
2943
2944         /* While processing this parameter, we need to pop the list of
2945            templates.  This is because the template parameter may
2946            itself be a reference to a parameter of an outer
2947            template.  */
2948
2949         hold_dpt = dpi->templates;
2950         dpi->templates = hold_dpt->next;
2951
2952         d_print_comp (dpi, d_left (a));
2953
2954         dpi->templates = hold_dpt;
2955
2956         return;
2957       }
2958
2959     case D_COMP_CTOR:
2960       d_print_comp (dpi, dc->u.s_ctor.name);
2961       return;
2962
2963     case D_COMP_DTOR:
2964       d_append_char (dpi, '~');
2965       d_print_comp (dpi, dc->u.s_dtor.name);
2966       return;
2967
2968     case D_COMP_VTABLE:
2969       d_append_string_constant (dpi, "vtable for ");
2970       d_print_comp (dpi, d_left (dc));
2971       return;
2972
2973     case D_COMP_VTT:
2974       d_append_string_constant (dpi, "VTT for ");
2975       d_print_comp (dpi, d_left (dc));
2976       return;
2977
2978     case D_COMP_CONSTRUCTION_VTABLE:
2979       d_append_string_constant (dpi, "construction vtable for ");
2980       d_print_comp (dpi, d_left (dc));
2981       d_append_string_constant (dpi, "-in-");
2982       d_print_comp (dpi, d_right (dc));
2983       return;
2984
2985     case D_COMP_TYPEINFO:
2986       d_append_string_constant (dpi, "typeinfo for ");
2987       d_print_comp (dpi, d_left (dc));
2988       return;
2989
2990     case D_COMP_TYPEINFO_NAME:
2991       d_append_string_constant (dpi, "typeinfo name for ");
2992       d_print_comp (dpi, d_left (dc));
2993       return;
2994
2995     case D_COMP_TYPEINFO_FN:
2996       d_append_string_constant (dpi, "typeinfo fn for ");
2997       d_print_comp (dpi, d_left (dc));
2998       return;
2999
3000     case D_COMP_THUNK:
3001       d_append_string_constant (dpi, "non-virtual thunk to ");
3002       d_print_comp (dpi, d_left (dc));
3003       return;
3004
3005     case D_COMP_VIRTUAL_THUNK:
3006       d_append_string_constant (dpi, "virtual thunk to ");
3007       d_print_comp (dpi, d_left (dc));
3008       return;
3009
3010     case D_COMP_COVARIANT_THUNK:
3011       d_append_string_constant (dpi, "covariant return thunk to ");
3012       d_print_comp (dpi, d_left (dc));
3013       return;
3014
3015     case D_COMP_JAVA_CLASS:
3016       d_append_string_constant (dpi, "java Class for ");
3017       d_print_comp (dpi, d_left (dc));
3018       return;
3019
3020     case D_COMP_GUARD:
3021       d_append_string_constant (dpi, "guard variable for ");
3022       d_print_comp (dpi, d_left (dc));
3023       return;
3024
3025     case D_COMP_REFTEMP:
3026       d_append_string_constant (dpi, "reference temporary for ");
3027       d_print_comp (dpi, d_left (dc));
3028       return;
3029
3030     case D_COMP_SUB_STD:
3031       d_append_buffer (dpi, dc->u.s_string.string, dc->u.s_string.len);
3032       return;
3033
3034     case D_COMP_RESTRICT:
3035     case D_COMP_VOLATILE:
3036     case D_COMP_CONST:
3037     case D_COMP_RESTRICT_THIS:
3038     case D_COMP_VOLATILE_THIS:
3039     case D_COMP_CONST_THIS:
3040     case D_COMP_VENDOR_TYPE_QUAL:
3041     case D_COMP_POINTER:
3042     case D_COMP_REFERENCE:
3043     case D_COMP_COMPLEX:
3044     case D_COMP_IMAGINARY:
3045       {
3046         /* We keep a list of modifiers on the stack.  */
3047         struct d_print_mod dpm;
3048
3049         dpm.next = dpi->modifiers;
3050         dpi->modifiers = &dpm;
3051         dpm.mod = dc;
3052         dpm.printed = 0;
3053         dpm.templates = dpi->templates;
3054
3055         d_print_comp (dpi, d_left (dc));
3056
3057         /* If the modifier didn't get printed by the type, print it
3058            now.  */
3059         if (! dpm.printed)
3060           d_print_mod (dpi, dc);
3061
3062         dpi->modifiers = dpm.next;
3063
3064         return;
3065       }
3066
3067     case D_COMP_BUILTIN_TYPE:
3068       if ((dpi->options & DMGL_JAVA) == 0)
3069         d_append_buffer (dpi, dc->u.s_builtin.type->name,
3070                          dc->u.s_builtin.type->len);
3071       else
3072         d_append_buffer (dpi, dc->u.s_builtin.type->java_name,
3073                          dc->u.s_builtin.type->java_len);
3074       return;
3075
3076     case D_COMP_VENDOR_TYPE:
3077       d_print_comp (dpi, d_left (dc));
3078       return;
3079
3080     case D_COMP_FUNCTION_TYPE:
3081       {
3082         if (d_left (dc) != NULL)
3083           {
3084             struct d_print_mod dpm;
3085
3086             /* We must pass this type down as a modifier in order to
3087                print it in the right location.  */
3088
3089             dpm.next = dpi->modifiers;
3090             dpi->modifiers = &dpm;
3091             dpm.mod = dc;
3092             dpm.printed = 0;
3093             dpm.templates = dpi->templates;
3094
3095             d_print_comp (dpi, d_left (dc));
3096
3097             dpi->modifiers = dpm.next;
3098
3099             if (dpm.printed)
3100               return;
3101
3102             d_append_char (dpi, ' ');
3103           }
3104
3105         d_print_function_type (dpi, dc, dpi->modifiers);
3106
3107         return;
3108       }
3109
3110     case D_COMP_ARRAY_TYPE:
3111       {
3112         struct d_print_mod dpm;
3113
3114         /* We must pass this type down as a modifier in order to print
3115            multi-dimensional arrays correctly.  */
3116
3117         dpm.next = dpi->modifiers;
3118         dpi->modifiers = &dpm;
3119         dpm.mod = dc;
3120         dpm.printed = 0;
3121         dpm.templates = dpi->templates;
3122
3123         d_print_comp (dpi, d_right (dc));
3124
3125         dpi->modifiers = dpm.next;
3126
3127         if (dpm.printed)
3128           return;
3129
3130         d_print_array_type (dpi, dc, dpi->modifiers);
3131
3132         return;
3133       }
3134
3135     case D_COMP_PTRMEM_TYPE:
3136       {
3137         struct d_print_mod dpm;
3138
3139         dpm.next = dpi->modifiers;
3140         dpi->modifiers = &dpm;
3141         dpm.mod = dc;
3142         dpm.printed = 0;
3143         dpm.templates = dpi->templates;
3144
3145         d_print_comp (dpi, d_right (dc));
3146
3147         /* If the modifier didn't get printed by the type, print it
3148            now.  */
3149         if (! dpm.printed)
3150           {
3151             d_append_char (dpi, ' ');
3152             d_print_comp (dpi, d_left (dc));
3153             d_append_string_constant (dpi, "::*");
3154           }
3155
3156         dpi->modifiers = dpm.next;
3157
3158         return;
3159       }
3160
3161     case D_COMP_ARGLIST:
3162     case D_COMP_TEMPLATE_ARGLIST:
3163       d_print_comp (dpi, d_left (dc));
3164       if (d_right (dc) != NULL)
3165         {
3166           d_append_string_constant (dpi, ", ");
3167           d_print_comp (dpi, d_right (dc));
3168         }
3169       return;
3170
3171     case D_COMP_OPERATOR:
3172       {
3173         char c;
3174
3175         d_append_string_constant (dpi, "operator");
3176         c = dc->u.s_operator.op->name[0];
3177         if (IS_LOWER (c))
3178           d_append_char (dpi, ' ');
3179         d_append_buffer (dpi, dc->u.s_operator.op->name,
3180                          dc->u.s_operator.op->len);
3181         return;
3182       }
3183
3184     case D_COMP_EXTENDED_OPERATOR:
3185       d_append_string_constant (dpi, "operator ");
3186       d_print_comp (dpi, dc->u.s_extended_operator.name);
3187       return;
3188
3189     case D_COMP_CAST:
3190       d_append_string_constant (dpi, "operator ");
3191       d_print_cast (dpi, dc);
3192       return;
3193
3194     case D_COMP_UNARY:
3195       if (d_left (dc)->type != D_COMP_CAST)
3196         d_print_expr_op (dpi, d_left (dc));
3197       else
3198         {
3199           d_append_string_constant (dpi, "((");
3200           d_print_cast (dpi, d_left (dc));
3201           d_append_char (dpi, ')');
3202         }
3203       d_append_char (dpi, '(');
3204       d_print_comp (dpi, d_right (dc));
3205       d_append_char (dpi, ')');
3206       if (d_left (dc)->type == D_COMP_CAST)
3207         d_append_char (dpi, ')');
3208       return;
3209
3210     case D_COMP_BINARY:
3211       if (d_right (dc)->type != D_COMP_BINARY_ARGS)
3212         {
3213           d_print_error (dpi);
3214           return;
3215         }
3216
3217       /* We wrap an expression which uses the greater-than operator in
3218          an extra layer of parens so that it does not get confused
3219          with the '>' which ends the template parameters.  */
3220       if (d_left (dc)->type == D_COMP_OPERATOR
3221           && d_left (dc)->u.s_operator.op->len == 1
3222           && d_left (dc)->u.s_operator.op->name[0] == '>')
3223         d_append_char (dpi, '(');
3224
3225       d_append_char (dpi, '(');
3226       d_print_comp (dpi, d_left (d_right (dc)));
3227       d_append_string_constant (dpi, ") ");
3228       d_print_expr_op (dpi, d_left (dc));
3229       d_append_string_constant (dpi, " (");
3230       d_print_comp (dpi, d_right (d_right (dc)));
3231       d_append_char (dpi, ')');
3232
3233       if (d_left (dc)->type == D_COMP_OPERATOR
3234           && d_left (dc)->u.s_operator.op->len == 1
3235           && d_left (dc)->u.s_operator.op->name[0] == '>')
3236         d_append_char (dpi, ')');
3237
3238       return;
3239
3240     case D_COMP_BINARY_ARGS:
3241       /* We should only see this as part of D_COMP_BINARY.  */
3242       d_print_error (dpi);
3243       return;
3244
3245     case D_COMP_TRINARY:
3246       if (d_right (dc)->type != D_COMP_TRINARY_ARG1
3247           || d_right (d_right (dc))->type != D_COMP_TRINARY_ARG2)
3248         {
3249           d_print_error (dpi);
3250           return;
3251         }
3252       d_append_char (dpi, '(');
3253       d_print_comp (dpi, d_left (d_right (dc)));
3254       d_append_string_constant (dpi, ") ");
3255       d_print_expr_op (dpi, d_left (dc));
3256       d_append_string_constant (dpi, " (");
3257       d_print_comp (dpi, d_left (d_right (d_right (dc))));
3258       d_append_string_constant (dpi, ") : (");
3259       d_print_comp (dpi, d_right (d_right (d_right (dc))));
3260       d_append_char (dpi, ')');
3261       return;
3262
3263     case D_COMP_TRINARY_ARG1:
3264     case D_COMP_TRINARY_ARG2:
3265       /* We should only see these are part of D_COMP_TRINARY.  */
3266       d_print_error (dpi);
3267       return;
3268
3269     case D_COMP_LITERAL:
3270     case D_COMP_LITERAL_NEG:
3271       /* For some builtin types, produce simpler output.  */
3272       if (d_left (dc)->type == D_COMP_BUILTIN_TYPE)
3273         {
3274           switch (d_left (dc)->u.s_builtin.type->print)
3275             {
3276             case D_PRINT_INT:
3277               if (d_right (dc)->type == D_COMP_NAME)
3278                 {
3279                   if (dc->type == D_COMP_LITERAL_NEG)
3280                     d_append_char (dpi, '-');
3281                   d_print_comp (dpi, d_right (dc));
3282                   return;
3283                 }
3284               break;
3285
3286             case D_PRINT_LONG:
3287               if (d_right (dc)->type == D_COMP_NAME)
3288                 {
3289                   if (dc->type == D_COMP_LITERAL_NEG)
3290                     d_append_char (dpi, '-');
3291                   d_print_comp (dpi, d_right (dc));
3292                   d_append_char (dpi, 'l');
3293                   return;
3294                 }
3295               break;
3296
3297             case D_PRINT_BOOL:
3298               if (d_right (dc)->type == D_COMP_NAME
3299                   && d_right (dc)->u.s_name.len == 1
3300                   && dc->type == D_COMP_LITERAL)
3301                 {
3302                   switch (d_right (dc)->u.s_name.s[0])
3303                     {
3304                     case '0':
3305                       d_append_string_constant (dpi, "false");
3306                       return;
3307                     case '1':
3308                       d_append_string_constant (dpi, "true");
3309                       return;
3310                     default:
3311                       break;
3312                     }
3313                 }
3314               break;
3315
3316             default:
3317               break;
3318             }
3319         }
3320
3321       d_append_char (dpi, '(');
3322       d_print_comp (dpi, d_left (dc));
3323       d_append_char (dpi, ')');
3324       if (dc->type == D_COMP_LITERAL_NEG)
3325         d_append_char (dpi, '-');
3326       d_print_comp (dpi, d_right (dc));
3327       return;
3328
3329     default:
3330       d_print_error (dpi);
3331       return;
3332     }
3333 }
3334
3335 /* Print a Java dentifier.  For Java we try to handle encoded extended
3336    Unicode characters.  The C++ ABI doesn't mention Unicode encoding,
3337    so we don't it for C++.  Characters are encoded as
3338    __U<hex-char>+_.  */
3339
3340 static void
3341 d_print_java_identifier (dpi, name, len)
3342      struct d_print_info *dpi;
3343      const char *name;
3344      int len;
3345 {
3346   const char *p;
3347   const char *end;
3348
3349   end = name + len;
3350   for (p = name; p < end; ++p)
3351     {
3352       if (end - p > 3
3353           && p[0] == '_'
3354           && p[1] == '_'
3355           && p[2] == 'U')
3356         {
3357           unsigned long c;
3358           const char *q;
3359
3360           c = 0;
3361           for (q = p + 3; q < end; ++q)
3362             {
3363               int dig;
3364
3365               if (IS_DIGIT (*q))
3366                 dig = *q - '0';
3367               else if (*q >= 'A' && *q <= 'F')
3368                 dig = *q - 'A' + 10;
3369               else if (*q >= 'a' && *q <= 'f')
3370                 dig = *q - 'a' + 10;
3371               else
3372                 break;
3373
3374               c = c * 16 + dig;
3375             }
3376           /* If the Unicode character is larger than 256, we don't try
3377              to deal with it here.  FIXME.  */
3378           if (q < end && *q == '_' && c < 256)
3379             {
3380               d_append_char (dpi, c);
3381               p = q;
3382               continue;
3383             }
3384         }
3385
3386       d_append_char (dpi, *p);
3387     }
3388 }
3389
3390 /* Print a list of modifiers.  SUFFIX is 1 if we are printing
3391    qualifiers on this after printing a function.  */
3392
3393 static void
3394 d_print_mod_list (dpi, mods, suffix)
3395      struct d_print_info *dpi;
3396      struct d_print_mod *mods;
3397      int suffix;
3398 {
3399   struct d_print_template *hold_dpt;
3400
3401   if (mods == NULL || d_print_saw_error (dpi))
3402     return;
3403
3404   if (mods->printed
3405       || (! suffix
3406           && (mods->mod->type == D_COMP_RESTRICT_THIS
3407               || mods->mod->type == D_COMP_VOLATILE_THIS
3408               || mods->mod->type == D_COMP_CONST_THIS)))
3409     {
3410       d_print_mod_list (dpi, mods->next, suffix);
3411       return;
3412     }
3413
3414   mods->printed = 1;
3415
3416   hold_dpt = dpi->templates;
3417   dpi->templates = mods->templates;
3418
3419   if (mods->mod->type == D_COMP_FUNCTION_TYPE)
3420     {
3421       d_print_function_type (dpi, mods->mod, mods->next);
3422       dpi->templates = hold_dpt;
3423       return;
3424     }
3425   else if (mods->mod->type == D_COMP_ARRAY_TYPE)
3426     {
3427       d_print_array_type (dpi, mods->mod, mods->next);
3428       dpi->templates = hold_dpt;
3429       return;
3430     }
3431   else if (mods->mod->type == D_COMP_LOCAL_NAME)
3432     {
3433       struct d_print_mod *hold_modifiers;
3434       struct d_comp *dc;
3435
3436       /* When this is on the modifier stack, we have pulled any
3437          qualifiers off the right argument already.  Otherwise, we
3438          print it as usual, but don't let the left argument see any
3439          modifiers.  */
3440
3441       hold_modifiers = dpi->modifiers;
3442       dpi->modifiers = NULL;
3443       d_print_comp (dpi, d_left (mods->mod));
3444       dpi->modifiers = hold_modifiers;
3445
3446       if ((dpi->options & DMGL_JAVA) == 0)
3447         d_append_string_constant (dpi, "::");
3448       else
3449         d_append_char (dpi, '.');
3450
3451       dc = d_right (mods->mod);
3452       while (dc->type == D_COMP_RESTRICT_THIS
3453              || dc->type == D_COMP_VOLATILE_THIS
3454              || dc->type == D_COMP_CONST_THIS)
3455         dc = d_left (dc);
3456
3457       d_print_comp (dpi, dc);
3458
3459       dpi->templates = hold_dpt;
3460       return;
3461     }
3462
3463   d_print_mod (dpi, mods->mod);
3464
3465   dpi->templates = hold_dpt;
3466
3467   d_print_mod_list (dpi, mods->next, suffix);
3468 }
3469
3470 /* Print a modifier.  */
3471
3472 static void
3473 d_print_mod (dpi, mod)
3474      struct d_print_info *dpi;
3475      const struct d_comp *mod;
3476 {
3477   switch (mod->type)
3478     {
3479     case D_COMP_RESTRICT:
3480     case D_COMP_RESTRICT_THIS:
3481       d_append_string_constant (dpi, " restrict");
3482       return;
3483     case D_COMP_VOLATILE:
3484     case D_COMP_VOLATILE_THIS:
3485       d_append_string_constant (dpi, " volatile");
3486       return;
3487     case D_COMP_CONST:
3488     case D_COMP_CONST_THIS:
3489       d_append_string_constant (dpi, " const");
3490       return;
3491     case D_COMP_VENDOR_TYPE_QUAL:
3492       d_append_char (dpi, ' ');
3493       d_print_comp (dpi, d_right (mod));
3494       return;
3495     case D_COMP_POINTER:
3496       /* There is no pointer symbol in Java.  */
3497       if ((dpi->options & DMGL_JAVA) == 0)
3498         d_append_char (dpi, '*');
3499       return;
3500     case D_COMP_REFERENCE:
3501       d_append_char (dpi, '&');
3502       return;
3503     case D_COMP_COMPLEX:
3504       d_append_string_constant (dpi, "complex ");
3505       return;
3506     case D_COMP_IMAGINARY:
3507       d_append_string_constant (dpi, "imaginary ");
3508       return;
3509     case D_COMP_PTRMEM_TYPE:
3510       if (d_last_char (dpi) != '(')
3511         d_append_char (dpi, ' ');
3512       d_print_comp (dpi, d_left (mod));
3513       d_append_string_constant (dpi, "::*");
3514       return;
3515     case D_COMP_TYPED_NAME:
3516       d_print_comp (dpi, d_left (mod));
3517       return;
3518     default:
3519       /* Otherwise, we have something that won't go back on the
3520          modifier stack, so we can just print it.  */
3521       d_print_comp (dpi, mod);
3522       return;
3523     }
3524 }
3525
3526 /* Print a function type, except for the return type.  */
3527
3528 static void
3529 d_print_function_type (dpi, dc, mods)
3530      struct d_print_info *dpi;
3531      const struct d_comp *dc;
3532      struct d_print_mod *mods;
3533 {
3534   int need_paren;
3535   int saw_mod;
3536   struct d_print_mod *p;
3537   struct d_print_mod *hold_modifiers;
3538
3539   need_paren = 0;
3540   saw_mod = 0;
3541   for (p = mods; p != NULL; p = p->next)
3542     {
3543       if (p->printed)
3544         break;
3545
3546       saw_mod = 1;
3547       switch (p->mod->type)
3548         {
3549         case D_COMP_RESTRICT:
3550         case D_COMP_VOLATILE:
3551         case D_COMP_CONST:
3552         case D_COMP_VENDOR_TYPE_QUAL:
3553         case D_COMP_POINTER:
3554         case D_COMP_REFERENCE:
3555         case D_COMP_COMPLEX:
3556         case D_COMP_IMAGINARY:
3557         case D_COMP_PTRMEM_TYPE:
3558           need_paren = 1;
3559           break;
3560         case D_COMP_RESTRICT_THIS:
3561         case D_COMP_VOLATILE_THIS:
3562         case D_COMP_CONST_THIS:
3563           break;
3564         default:
3565           break;
3566         }
3567       if (need_paren)
3568         break;
3569     }
3570
3571   if (d_left (dc) != NULL && ! saw_mod)
3572     need_paren = 1;
3573
3574   if (need_paren)
3575     {
3576       switch (d_last_char (dpi))
3577         {
3578         case ' ':
3579         case '(':
3580         case '*':
3581           break;
3582
3583         default:
3584           d_append_char (dpi, ' ');
3585           break;
3586         }
3587
3588       d_append_char (dpi, '(');
3589     }
3590
3591   hold_modifiers = dpi->modifiers;
3592   dpi->modifiers = NULL;
3593
3594   d_print_mod_list (dpi, mods, 0);
3595
3596   if (need_paren)
3597     d_append_char (dpi, ')');
3598
3599   d_append_char (dpi, '(');
3600
3601   if (d_right (dc) != NULL)
3602     d_print_comp (dpi, d_right (dc));
3603
3604   d_append_char (dpi, ')');
3605
3606   d_print_mod_list (dpi, mods, 1);
3607
3608   dpi->modifiers = hold_modifiers;
3609 }
3610
3611 /* Print an array type, except for the element type.  */
3612
3613 static void
3614 d_print_array_type (dpi, dc, mods)
3615      struct d_print_info *dpi;
3616      const struct d_comp *dc;
3617      struct d_print_mod *mods;
3618 {
3619   int need_space;
3620
3621   need_space = 1;
3622   if (mods != NULL)
3623     {
3624       int need_paren;
3625       struct d_print_mod *p;
3626
3627       need_paren = 0;
3628       for (p = mods; p != NULL; p = p->next)
3629         {
3630           if (p->printed)
3631             break;
3632
3633           if (p->mod->type == D_COMP_ARRAY_TYPE)
3634             {
3635               need_space = 0;
3636               break;
3637             }
3638           else
3639             {
3640               need_paren = 1;
3641               need_space = 1;
3642               break;
3643             }
3644         }
3645
3646       if (need_paren)
3647         d_append_string_constant (dpi, " (");
3648
3649       d_print_mod_list (dpi, mods, 0);
3650
3651       if (need_paren)
3652         d_append_char (dpi, ')');
3653     }
3654
3655   if (need_space)
3656     d_append_char (dpi, ' ');
3657
3658   d_append_char (dpi, '[');
3659
3660   if (d_left (dc) != NULL)
3661     d_print_comp (dpi, d_left (dc));
3662
3663   d_append_char (dpi, ']');
3664 }
3665
3666 /* Print an operator in an expression.  */
3667
3668 static void
3669 d_print_expr_op (dpi, dc)
3670      struct d_print_info *dpi;
3671      const struct d_comp *dc;
3672 {
3673   if (dc->type == D_COMP_OPERATOR)
3674     d_append_buffer (dpi, dc->u.s_operator.op->name,
3675                      dc->u.s_operator.op->len);
3676   else
3677     d_print_comp (dpi, dc);
3678 }
3679
3680 /* Print a cast.  */
3681
3682 static void
3683 d_print_cast (dpi, dc)
3684      struct d_print_info *dpi;
3685      const struct d_comp *dc;
3686 {
3687   if (d_left (dc)->type != D_COMP_TEMPLATE)
3688     d_print_comp (dpi, d_left (dc));
3689   else
3690     {
3691       struct d_print_mod *hold_dpm;
3692       struct d_print_template dpt;
3693
3694       /* It appears that for a templated cast operator, we need to put
3695          the template parameters in scope for the operator name, but
3696          not for the parameters.  The effect is that we need to handle
3697          the template printing here.  */
3698
3699       hold_dpm = dpi->modifiers;
3700       dpi->modifiers = NULL;
3701
3702       dpt.next = dpi->templates;
3703       dpi->templates = &dpt;
3704       dpt.template = d_left (dc);
3705
3706       d_print_comp (dpi, d_left (d_left (dc)));
3707
3708       dpi->templates = dpt.next;
3709
3710       if (d_last_char (dpi) == '<')
3711         d_append_char (dpi, ' ');
3712       d_append_char (dpi, '<');
3713       d_print_comp (dpi, d_right (d_left (dc)));
3714       /* Avoid generating two consecutive '>' characters, to avoid
3715          the C++ syntactic ambiguity.  */
3716       if (d_last_char (dpi) == '>')
3717         d_append_char (dpi, ' ');
3718       d_append_char (dpi, '>');
3719
3720       dpi->modifiers = hold_dpm;
3721     }
3722 }
3723
3724 /* Initialize the information structure we use to pass around
3725    information.  */
3726
3727 static void
3728 d_init_info (mangled, options, len, di)
3729      const char *mangled;
3730      int options;
3731      size_t len;
3732      struct d_info *di;
3733 {
3734   di->s = mangled;
3735   di->send = mangled + len;
3736   di->options = options;
3737
3738   di->n = mangled;
3739
3740   /* We can not need more components than twice the number of chars in
3741      the mangled string.  Most components correspond directly to
3742      chars, but the ARGLIST types are exceptions.  */
3743   di->num_comps = 2 * len;
3744   di->next_comp = 0;
3745
3746   /* Similarly, we can not need more substitutions than there are
3747      chars in the mangled string.  */
3748   di->num_subs = len;
3749   di->next_sub = 0;
3750   di->did_subs = 0;
3751
3752   di->last_name = NULL;
3753
3754   di->expansion = 0;
3755 }
3756
3757 /* Entry point for the demangler.  If MANGLED is a g++ v3 ABI mangled
3758    name, return a buffer allocated with malloc holding the demangled
3759    name.  OPTIONS is the usual libiberty demangler options.  On
3760    success, this sets *PALC to the allocated size of the returned
3761    buffer.  On failure, this sets *PALC to 0 for a bad name, or 1 for
3762    a memory allocation failure.  On failure, this returns NULL.  */
3763
3764 static char *
3765 d_demangle (mangled, options, palc)
3766      const char* mangled;
3767      int options;
3768      size_t *palc;
3769 {
3770   size_t len;
3771   int type;
3772   struct d_info di;
3773   struct d_comp *dc;
3774   int estimate;
3775   char *ret;
3776
3777   *palc = 0;
3778
3779   len = strlen (mangled);
3780
3781   if (mangled[0] == '_' && mangled[1] == 'Z')
3782     type = 0;
3783   else if (strncmp (mangled, "_GLOBAL_", 8) == 0
3784            && (mangled[8] == '.' || mangled[8] == '_' || mangled[8] == '$')
3785            && (mangled[9] == 'D' || mangled[9] == 'I')
3786            && mangled[10] == '_')
3787     {
3788       char *r;
3789
3790       r = malloc (40 + len - 11);
3791       if (r == NULL)
3792         *palc = 1;
3793       else
3794         {
3795           if (mangled[9] == 'I')
3796             strcpy (r, "global constructors keyed to ");
3797           else
3798             strcpy (r, "global destructors keyed to ");
3799           strcat (r, mangled + 11);
3800         }
3801       return r;
3802     }
3803   else
3804     {
3805       if ((options & DMGL_TYPES) == 0)
3806         return NULL;
3807       type = 1;
3808     }
3809
3810   d_init_info (mangled, options, len, &di);
3811
3812   {
3813 #ifdef CP_DYNAMIC_ARRAYS
3814     __extension__ struct d_comp comps[di.num_comps];
3815     __extension__ struct d_comp *subs[di.num_subs];
3816
3817     di.comps = &comps[0];
3818     di.subs = &subs[0];
3819 #else
3820     di.comps = (struct d_comp *) malloc (di.num_comps
3821                                          * sizeof (struct d_comp));
3822     di.subs = (struct d_comp **) malloc (di.num_subs
3823                                          * sizeof (struct d_comp *));
3824     if (di.comps == NULL || di.subs == NULL)
3825       {
3826         if (di.comps != NULL)
3827           free (di.comps);
3828         if (di.subs != NULL)
3829           free (di.subs);
3830         *palc = 1;
3831         return NULL;
3832       }
3833 #endif
3834
3835     if (! type)
3836       dc = d_mangled_name (&di, 1);
3837     else
3838       dc = d_type (&di);
3839
3840     /* If DMGL_PARAMS is set, then if we didn't consume the entire
3841        mangled string, then we didn't successfully demangle it.  If
3842        DMGL_PARAMS is not set, we didn't look at the trailing
3843        parameters.  */
3844     if (((options & DMGL_PARAMS) != 0) && d_peek_char (&di) != '\0')
3845       dc = NULL;
3846
3847 #ifdef CP_DEMANGLE_DEBUG
3848     if (dc == NULL)
3849       printf ("failed demangling\n");
3850     else
3851       d_dump (dc, 0);
3852 #endif
3853
3854     /* We try to guess the length of the demangled string, to minimize
3855        calls to realloc during demangling.  */
3856     estimate = len + di.expansion + 10 * di.did_subs;
3857     estimate += estimate / 8;
3858
3859     ret = NULL;
3860     if (dc != NULL)
3861       ret = d_print (options, dc, estimate, palc);
3862
3863 #ifndef CP_DYNAMIC_ARRAYS
3864     free (di.comps);
3865     free (di.subs);
3866 #endif
3867
3868 #ifdef CP_DEMANGLE_DEBUG
3869     if (ret != NULL)
3870       {
3871         int rlen;
3872
3873         rlen = strlen (ret);
3874         if (rlen > 2 * estimate)
3875           printf ("*** Length %d much greater than estimate %d\n",
3876                   rlen, estimate);
3877         else if (rlen > estimate)
3878           printf ("*** Length %d greater than estimate %d\n",
3879                   rlen, estimate);
3880         else if (rlen < estimate / 2)
3881           printf ("*** Length %d much less than estimate %d\n",
3882                   rlen, estimate);
3883       }
3884 #endif
3885   }
3886
3887   return ret;
3888 }
3889
3890 #if defined(IN_LIBGCC2) || defined(IN_GLIBCPP_V3)
3891
3892 extern char *__cxa_demangle PARAMS ((const char *, char *, size_t *, int *));
3893
3894 /* ia64 ABI-mandated entry point in the C++ runtime library for
3895    performing demangling.  MANGLED_NAME is a NUL-terminated character
3896    string containing the name to be demangled.
3897
3898    OUTPUT_BUFFER is a region of memory, allocated with malloc, of
3899    *LENGTH bytes, into which the demangled name is stored.  If
3900    OUTPUT_BUFFER is not long enough, it is expanded using realloc.
3901    OUTPUT_BUFFER may instead be NULL; in that case, the demangled name
3902    is placed in a region of memory allocated with malloc.
3903
3904    If LENGTH is non-NULL, the length of the buffer conaining the
3905    demangled name, is placed in *LENGTH.
3906
3907    The return value is a pointer to the start of the NUL-terminated
3908    demangled name, or NULL if the demangling fails.  The caller is
3909    responsible for deallocating this memory using free.
3910
3911    *STATUS is set to one of the following values:
3912       0: The demangling operation succeeded.
3913      -1: A memory allocation failure occurred.
3914      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
3915      -3: One of the arguments is invalid.
3916
3917    The demangling is performed using the C++ ABI mangling rules, with
3918    GNU extensions.  */
3919
3920 char *
3921 __cxa_demangle (mangled_name, output_buffer, length, status)
3922      const char *mangled_name;
3923      char *output_buffer;
3924      size_t *length;
3925      int *status;
3926 {
3927   char *demangled;
3928   size_t alc;
3929
3930   if (status == NULL)
3931     return NULL;
3932
3933   if (mangled_name == NULL)
3934     {
3935       *status = -3;
3936       return NULL;
3937     }
3938
3939   if (output_buffer != NULL && length == NULL)
3940     {
3941       *status = -3;
3942       return NULL;
3943     }
3944
3945   demangled = d_demangle (mangled_name, DMGL_TYPES, &alc);
3946
3947   if (demangled == NULL)
3948     {
3949       if (alc == 1)
3950         *status = -1;
3951       else
3952         *status = -2;
3953       return NULL;
3954     }
3955
3956   if (output_buffer == NULL)
3957     {
3958       if (length != NULL)
3959         *length = alc;
3960     }
3961   else
3962     {
3963       if (strlen (demangled) < *length)
3964         {
3965           strcpy (output_buffer, demangled);
3966           free (demangled);
3967           demangled = output_buffer;
3968         }
3969       else
3970         {
3971           free (output_buffer);
3972           *length = alc;
3973         }
3974     }
3975
3976   *status = 0;
3977
3978   return demangled;
3979 }
3980
3981 #else /* ! (IN_LIBGCC2 || IN_GLIBCPP_V3) */
3982
3983 /* Entry point for libiberty demangler.  If MANGLED is a g++ v3 ABI
3984    mangled name, return a buffer allocated with malloc holding the
3985    demangled name.  Otherwise, return NULL.  */
3986
3987 char *
3988 cplus_demangle_v3 (mangled, options)
3989      const char* mangled;
3990      int options;
3991 {
3992   size_t alc;
3993
3994   return d_demangle (mangled, options, &alc);
3995 }
3996
3997 /* Demangle a Java symbol.  Java uses a subset of the V3 ABI C++ mangling 
3998    conventions, but the output formatting is a little different.
3999    This instructs the C++ demangler not to emit pointer characters ("*"), and 
4000    to use Java's namespace separator symbol ("." instead of "::").  It then 
4001    does an additional pass over the demangled output to replace instances 
4002    of JArray<TYPE> with TYPE[].  */
4003
4004 char *
4005 java_demangle_v3 (mangled)
4006      const char* mangled;
4007 {
4008   size_t alc;
4009   char *demangled;
4010   int nesting;
4011   char *from;
4012   char *to;
4013
4014   demangled = d_demangle (mangled, DMGL_JAVA | DMGL_PARAMS, &alc);
4015
4016   if (demangled == NULL)
4017     return NULL;
4018
4019   nesting = 0;
4020   from = demangled;
4021   to = from;
4022   while (*from != '\0')
4023     {
4024       if (strncmp (from, "JArray<", 7) == 0)
4025         {
4026           from += 7;
4027           ++nesting;
4028         }
4029       else if (nesting > 0 && *from == '>')
4030         {
4031           while (to > demangled && to[-1] == ' ')
4032             --to;
4033           *to++ = '[';
4034           *to++ = ']';
4035           --nesting;
4036           ++from;
4037         }
4038       else
4039         *to++ = *from++;
4040     }
4041
4042   *to = '\0';
4043
4044   return demangled;
4045 }
4046
4047 #endif /* IN_LIBGCC2 || IN_GLIBCPP_V3 */
4048
4049 #ifndef IN_GLIBCPP_V3
4050
4051 /* Demangle a string in order to find out whether it is a constructor
4052    or destructor.  Return non-zero on success.  Set *CTOR_KIND and
4053    *DTOR_KIND appropriately.  */
4054
4055 static int
4056 is_ctor_or_dtor (mangled, ctor_kind, dtor_kind)
4057      const char *mangled;
4058      enum gnu_v3_ctor_kinds *ctor_kind;
4059      enum gnu_v3_dtor_kinds *dtor_kind;
4060 {
4061   struct d_info di;
4062   struct d_comp *dc;
4063   int ret;
4064
4065   *ctor_kind = (enum gnu_v3_ctor_kinds) 0;
4066   *dtor_kind = (enum gnu_v3_dtor_kinds) 0;
4067
4068   d_init_info (mangled, DMGL_GNU_V3, strlen (mangled), &di);
4069
4070   {
4071 #ifdef CP_DYNAMIC_ARRAYS
4072     __extension__ struct d_comp comps[di.num_comps];
4073     __extension__ struct d_comp *subs[di.num_subs];
4074
4075     di.comps = &comps[0];
4076     di.subs = &subs[0];
4077 #else
4078     di.comps = (struct d_comp *) malloc (di.num_comps
4079                                          * sizeof (struct d_comp));
4080     di.subs = (struct d_comp **) malloc (di.num_subs
4081                                          * sizeof (struct d_comp *));
4082     if (di.comps == NULL || di.subs == NULL)
4083       {
4084         if (di.comps != NULL)
4085           free (di.comps);
4086         if (di.subs != NULL)
4087           free (di.subs);
4088         return 0;
4089       }
4090 #endif
4091
4092     dc = d_mangled_name (&di, 1);
4093
4094     /* Note that because we did not pass DMGL_PARAMS, we don't expect
4095        to demangle the entire string.  */
4096
4097     ret = 0;
4098     while (dc != NULL)
4099       {
4100         switch (dc->type)
4101           {
4102           default:
4103             dc = NULL;
4104             break;
4105           case D_COMP_TYPED_NAME:
4106           case D_COMP_TEMPLATE:
4107           case D_COMP_RESTRICT_THIS:
4108           case D_COMP_VOLATILE_THIS:
4109           case D_COMP_CONST_THIS:
4110             dc = d_left (dc);
4111             break;
4112           case D_COMP_QUAL_NAME:
4113           case D_COMP_LOCAL_NAME:
4114             dc = d_right (dc);
4115             break;
4116           case D_COMP_CTOR:
4117             *ctor_kind = dc->u.s_ctor.kind;
4118             ret = 1;
4119             dc = NULL;
4120             break;
4121           case D_COMP_DTOR:
4122             *dtor_kind = dc->u.s_dtor.kind;
4123             ret = 1;
4124             dc = NULL;
4125             break;
4126           }
4127       }
4128
4129 #ifndef CP_DYNAMIC_ARRAYS
4130     free (di.subs);
4131     free (di.comps);
4132 #endif
4133   }
4134
4135   return ret;
4136 }
4137
4138 /* Return whether NAME is the mangled form of a g++ V3 ABI constructor
4139    name.  A non-zero return indicates the type of constructor.  */
4140
4141 enum gnu_v3_ctor_kinds
4142 is_gnu_v3_mangled_ctor (name)
4143      const char *name;
4144 {
4145   enum gnu_v3_ctor_kinds ctor_kind;
4146   enum gnu_v3_dtor_kinds dtor_kind;
4147
4148   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
4149     return (enum gnu_v3_ctor_kinds) 0;
4150   return ctor_kind;
4151 }
4152
4153
4154 /* Return whether NAME is the mangled form of a g++ V3 ABI destructor
4155    name.  A non-zero return indicates the type of destructor.  */
4156
4157 enum gnu_v3_dtor_kinds
4158 is_gnu_v3_mangled_dtor (name)
4159      const char *name;
4160 {
4161   enum gnu_v3_ctor_kinds ctor_kind;
4162   enum gnu_v3_dtor_kinds dtor_kind;
4163
4164   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
4165     return (enum gnu_v3_dtor_kinds) 0;
4166   return dtor_kind;
4167 }
4168
4169 #endif /* IN_GLIBCPP_V3 */
4170
4171 #ifdef STANDALONE_DEMANGLER
4172
4173 #include "getopt.h"
4174 #include "dyn-string.h"
4175
4176 static void print_usage PARAMS ((FILE* fp, int exit_value));
4177
4178 #define IS_ALPHA(CHAR)                                                  \
4179   (((CHAR) >= 'a' && (CHAR) <= 'z')                                     \
4180    || ((CHAR) >= 'A' && (CHAR) <= 'Z'))
4181
4182 /* Non-zero if CHAR is a character than can occur in a mangled name.  */
4183 #define is_mangled_char(CHAR)                                           \
4184   (IS_ALPHA (CHAR) || IS_DIGIT (CHAR)                                   \
4185    || (CHAR) == '_' || (CHAR) == '.' || (CHAR) == '$')
4186
4187 /* The name of this program, as invoked.  */
4188 const char* program_name;
4189
4190 /* Prints usage summary to FP and then exits with EXIT_VALUE.  */
4191
4192 static void
4193 print_usage (fp, exit_value)
4194      FILE* fp;
4195      int exit_value;
4196 {
4197   fprintf (fp, "Usage: %s [options] [names ...]\n", program_name);
4198   fprintf (fp, "Options:\n");
4199   fprintf (fp, "  -h,--help       Display this message.\n");
4200   fprintf (fp, "  -p,--no-params  Don't display function parameters\n");
4201   fprintf (fp, "  -v,--verbose    Produce verbose demanglings.\n");
4202   fprintf (fp, "If names are provided, they are demangled.  Otherwise filters standard input.\n");
4203
4204   exit (exit_value);
4205 }
4206
4207 /* Option specification for getopt_long.  */
4208 static const struct option long_options[] = 
4209 {
4210   { "help",      no_argument, NULL, 'h' },
4211   { "no-params", no_argument, NULL, 'p' },
4212   { "verbose",   no_argument, NULL, 'v' },
4213   { NULL,        no_argument, NULL, 0   },
4214 };
4215
4216 /* Main entry for a demangling filter executable.  It will demangle
4217    its command line arguments, if any.  If none are provided, it will
4218    filter stdin to stdout, replacing any recognized mangled C++ names
4219    with their demangled equivalents.  */
4220
4221 int
4222 main (argc, argv)
4223      int argc;
4224      char *argv[];
4225 {
4226   int i;
4227   int opt_char;
4228   int options = DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES;
4229
4230   /* Use the program name of this program, as invoked.  */
4231   program_name = argv[0];
4232
4233   /* Parse options.  */
4234   do 
4235     {
4236       opt_char = getopt_long (argc, argv, "hpv", long_options, NULL);
4237       switch (opt_char)
4238         {
4239         case '?':  /* Unrecognized option.  */
4240           print_usage (stderr, 1);
4241           break;
4242
4243         case 'h':
4244           print_usage (stdout, 0);
4245           break;
4246
4247         case 'p':
4248           options &= ~ DMGL_PARAMS;
4249           break;
4250
4251         case 'v':
4252           options |= DMGL_VERBOSE;
4253           break;
4254         }
4255     }
4256   while (opt_char != -1);
4257
4258   if (optind == argc) 
4259     /* No command line arguments were provided.  Filter stdin.  */
4260     {
4261       dyn_string_t mangled = dyn_string_new (3);
4262       char *s;
4263
4264       /* Read all of input.  */
4265       while (!feof (stdin))
4266         {
4267           char c;
4268
4269           /* Pile characters into mangled until we hit one that can't
4270              occur in a mangled name.  */
4271           c = getchar ();
4272           while (!feof (stdin) && is_mangled_char (c))
4273             {
4274               dyn_string_append_char (mangled, c);
4275               if (feof (stdin))
4276                 break;
4277               c = getchar ();
4278             }
4279
4280           if (dyn_string_length (mangled) > 0)
4281             {
4282               s = cplus_demangle_v3 (dyn_string_buf (mangled), options);
4283
4284               if (s != NULL)
4285                 {
4286                   fputs (s, stdout);
4287                   free (s);
4288                 }
4289               else
4290                 {
4291                   /* It might not have been a mangled name.  Print the
4292                      original text.  */
4293                   fputs (dyn_string_buf (mangled), stdout);
4294                 }
4295
4296               dyn_string_clear (mangled);
4297             }
4298
4299           /* If we haven't hit EOF yet, we've read one character that
4300              can't occur in a mangled name, so print it out.  */
4301           if (!feof (stdin))
4302             putchar (c);
4303         }
4304
4305       dyn_string_delete (mangled);
4306     }
4307   else
4308     /* Demangle command line arguments.  */
4309     {
4310       /* Loop over command line arguments.  */
4311       for (i = optind; i < argc; ++i)
4312         {
4313           char *s;
4314
4315           /* Attempt to demangle.  */
4316           s = cplus_demangle_v3 (argv[i], options);
4317
4318           /* If it worked, print the demangled name.  */
4319           if (s != NULL)
4320             {
4321               printf ("%s\n", s);
4322               free (s);
4323             }
4324           else
4325             fprintf (stderr, "Failed: %s\n", argv[i]);
4326         }
4327     }
4328
4329   return 0;
4330 }
4331
4332 #endif /* STANDALONE_DEMANGLER */