OSDN Git Service

a5d18170536b95326c7b906c6ae1fe1abc27972d
[pf3gnuchains/gcc-fork.git] / libiberty / cp-demangle.c
1 /* Demangler for g++ V3 ABI.
2    Copyright (C) 2003, 2004 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
1113           /* If the top level is a D_COMP_LOCAL_NAME, then there may
1114              be CV-qualifiers on its right argument which really apply
1115              here; this happens when parsing a class which is local to
1116              a function.  */
1117           if (dc->type == D_COMP_LOCAL_NAME)
1118             {
1119               struct d_comp *dcr;
1120
1121               dcr = d_right (dc);
1122               while (dcr->type == D_COMP_RESTRICT_THIS
1123                      || dcr->type == D_COMP_VOLATILE_THIS
1124                      || dcr->type == D_COMP_CONST_THIS)
1125                 dcr = d_left (dcr);
1126               dc->u.s_binary.right = dcr;
1127             }
1128
1129           return dc;
1130         }
1131
1132       peek = d_peek_char (di);
1133       if (peek == '\0' || peek == 'E')
1134         return dc;
1135       return d_make_comp (di, D_COMP_TYPED_NAME, dc,
1136                           d_bare_function_type (di, has_return_type (dc)));
1137     }
1138 }
1139
1140 /* <name> ::= <nested-name>
1141           ::= <unscoped-name>
1142           ::= <unscoped-template-name> <template-args>
1143           ::= <local-name>
1144
1145    <unscoped-name> ::= <unqualified-name>
1146                    ::= St <unqualified-name>
1147
1148    <unscoped-template-name> ::= <unscoped-name>
1149                             ::= <substitution>
1150 */
1151
1152 static struct d_comp *
1153 d_name (di)
1154      struct d_info *di;
1155 {
1156   char peek = d_peek_char (di);
1157   struct d_comp *dc;
1158
1159   switch (peek)
1160     {
1161     case 'N':
1162       return d_nested_name (di);
1163
1164     case 'Z':
1165       return d_local_name (di);
1166
1167     case 'S':
1168       {
1169         int subst;
1170
1171         if (d_peek_next_char (di) != 't')
1172           {
1173             dc = d_substitution (di, 0);
1174             subst = 1;
1175           }
1176         else
1177           {
1178             d_advance (di, 2);
1179             dc = d_make_comp (di, D_COMP_QUAL_NAME, d_make_name (di, "std", 3),
1180                               d_unqualified_name (di));
1181             di->expansion += 3;
1182             subst = 0;
1183           }
1184
1185         if (d_peek_char (di) != 'I')
1186           {
1187             /* The grammar does not permit this case to occur if we
1188                called d_substitution() above (i.e., subst == 1).  We
1189                don't bother to check.  */
1190           }
1191         else
1192           {
1193             /* This is <template-args>, which means that we just saw
1194                <unscoped-template-name>, which is a substitution
1195                candidate if we didn't just get it from a
1196                substitution.  */
1197             if (! subst)
1198               {
1199                 if (! d_add_substitution (di, dc))
1200                   return NULL;
1201               }
1202             dc = d_make_comp (di, D_COMP_TEMPLATE, dc, d_template_args (di));
1203           }
1204
1205         return dc;
1206       }
1207
1208     default:
1209       dc = d_unqualified_name (di);
1210       if (d_peek_char (di) == 'I')
1211         {
1212           /* This is <template-args>, which means that we just saw
1213              <unscoped-template-name>, which is a substitution
1214              candidate.  */
1215           if (! d_add_substitution (di, dc))
1216             return NULL;
1217           dc = d_make_comp (di, D_COMP_TEMPLATE, dc, d_template_args (di));
1218         }
1219       return dc;
1220     }
1221 }
1222
1223 /* <nested-name> ::= N [<CV-qualifiers>] <prefix> <unqualified-name> E
1224                  ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1225 */
1226
1227 static struct d_comp *
1228 d_nested_name (di)
1229      struct d_info *di;
1230 {
1231   struct d_comp *ret;
1232   struct d_comp **pret;
1233
1234   if (d_next_char (di) != 'N')
1235     return NULL;
1236
1237   pret = d_cv_qualifiers (di, &ret, 1);
1238   if (pret == NULL)
1239     return NULL;
1240
1241   *pret = d_prefix (di);
1242   if (*pret == NULL)
1243     return NULL;
1244
1245   if (d_next_char (di) != 'E')
1246     return NULL;
1247
1248   return ret;
1249 }
1250
1251 /* <prefix> ::= <prefix> <unqualified-name>
1252             ::= <template-prefix> <template-args>
1253             ::= <template-param>
1254             ::=
1255             ::= <substitution>
1256
1257    <template-prefix> ::= <prefix> <(template) unqualified-name>
1258                      ::= <template-param>
1259                      ::= <substitution>
1260 */
1261
1262 static struct d_comp *
1263 d_prefix (di)
1264      struct d_info *di;
1265 {
1266   struct d_comp *ret = NULL;
1267
1268   while (1)
1269     {
1270       char peek;
1271       enum d_comp_type comb_type;
1272       struct d_comp *dc;
1273
1274       peek = d_peek_char (di);
1275       if (peek == '\0')
1276         return NULL;
1277
1278       /* The older code accepts a <local-name> here, but I don't see
1279          that in the grammar.  The older code does not accept a
1280          <template-param> here.  */
1281
1282       comb_type = D_COMP_QUAL_NAME;
1283       if (IS_DIGIT (peek)
1284           || IS_LOWER (peek)
1285           || peek == 'C'
1286           || peek == 'D')
1287         dc = d_unqualified_name (di);
1288       else if (peek == 'S')
1289         dc = d_substitution (di, 1);
1290       else if (peek == 'I')
1291         {
1292           if (ret == NULL)
1293             return NULL;
1294           comb_type = D_COMP_TEMPLATE;
1295           dc = d_template_args (di);
1296         }
1297       else if (peek == 'T')
1298         dc = d_template_param (di);
1299       else if (peek == 'E')
1300         return ret;
1301       else
1302         return NULL;
1303
1304       if (ret == NULL)
1305         ret = dc;
1306       else
1307         ret = d_make_comp (di, comb_type, ret, dc);
1308
1309       if (peek != 'S' && d_peek_char (di) != 'E')
1310         {
1311           if (! d_add_substitution (di, ret))
1312             return NULL;
1313         }
1314     }
1315 }
1316
1317 /* <unqualified-name> ::= <operator-name>
1318                       ::= <ctor-dtor-name>
1319                       ::= <source-name>
1320 */
1321
1322 static struct d_comp *
1323 d_unqualified_name (di)
1324      struct d_info *di;
1325 {
1326   char peek;
1327
1328   peek = d_peek_char (di);
1329   if (IS_DIGIT (peek))
1330     return d_source_name (di);
1331   else if (IS_LOWER (peek))
1332     {
1333       struct d_comp *ret;
1334
1335       ret = d_operator_name (di);
1336       if (ret != NULL && ret->type == D_COMP_OPERATOR)
1337         di->expansion += sizeof "operator" + ret->u.s_operator.op->len - 2;
1338       return ret;
1339     }
1340   else if (peek == 'C' || peek == 'D')
1341     return d_ctor_dtor_name (di);
1342   else
1343     return NULL;
1344 }
1345
1346 /* <source-name> ::= <(positive length) number> <identifier>  */
1347
1348 static struct d_comp *
1349 d_source_name (di)
1350      struct d_info *di;
1351 {
1352   long len;
1353   struct d_comp *ret;
1354
1355   len = d_number (di);
1356   if (len <= 0)
1357     return NULL;
1358   ret = d_identifier (di, len);
1359   di->last_name = ret;
1360   return ret;
1361 }
1362
1363 /* number ::= [n] <(non-negative decimal integer)>  */
1364
1365 static long
1366 d_number (di)
1367      struct d_info *di;
1368 {
1369   int negative;
1370   char peek;
1371   long ret;
1372
1373   negative = 0;
1374   peek = d_peek_char (di);
1375   if (peek == 'n')
1376     {
1377       negative = 1;
1378       d_advance (di, 1);
1379       peek = d_peek_char (di);
1380     }
1381
1382   ret = 0;
1383   while (1)
1384     {
1385       if (! IS_DIGIT (peek))
1386         {
1387           if (negative)
1388             ret = - ret;
1389           return ret;
1390         }
1391       ret = ret * 10 + peek - '0';
1392       d_advance (di, 1);
1393       peek = d_peek_char (di);
1394     }
1395 }
1396
1397 /* identifier ::= <(unqualified source code identifier)>  */
1398
1399 static struct d_comp *
1400 d_identifier (di, len)
1401      struct d_info *di;
1402      int len;
1403 {
1404   const char *name;
1405
1406   name = d_str (di);
1407
1408   if (di->send - name < len)
1409     return NULL;
1410
1411   d_advance (di, len);
1412
1413   /* A Java mangled name may have a trailing '$' if it is a C++
1414      keyword.  This '$' is not included in the length count.  We just
1415      ignore the '$'.  */
1416   if ((di->options & DMGL_JAVA) != 0
1417       && d_peek_char (di) == '$')
1418     d_advance (di, 1);
1419
1420   /* Look for something which looks like a gcc encoding of an
1421      anonymous namespace, and replace it with a more user friendly
1422      name.  */
1423   if (len >= (int) ANONYMOUS_NAMESPACE_PREFIX_LEN + 2
1424       && memcmp (name, ANONYMOUS_NAMESPACE_PREFIX,
1425                  ANONYMOUS_NAMESPACE_PREFIX_LEN) == 0)
1426     {
1427       const char *s;
1428
1429       s = name + ANONYMOUS_NAMESPACE_PREFIX_LEN;
1430       if ((*s == '.' || *s == '_' || *s == '$')
1431           && s[1] == 'N')
1432         {
1433           di->expansion -= len - sizeof "(anonymous namespace)";
1434           return d_make_name (di, "(anonymous namespace)",
1435                               sizeof "(anonymous namespace)" - 1);
1436         }
1437     }
1438
1439   return d_make_name (di, name, len);
1440 }
1441
1442 /* operator_name ::= many different two character encodings.
1443                  ::= cv <type>
1444                  ::= v <digit> <source-name>
1445 */
1446
1447 #define NL(s) s, (sizeof s) - 1
1448
1449 static const struct d_operator_info d_operators[] =
1450 {
1451   { "aN", NL ("&="),        2 },
1452   { "aS", NL ("="),         2 },
1453   { "aa", NL ("&&"),        2 },
1454   { "ad", NL ("&"),         1 },
1455   { "an", NL ("&"),         2 },
1456   { "cl", NL ("()"),        0 },
1457   { "cm", NL (","),         2 },
1458   { "co", NL ("~"),         1 },
1459   { "dV", NL ("/="),        2 },
1460   { "da", NL ("delete[]"),  1 },
1461   { "de", NL ("*"),         1 },
1462   { "dl", NL ("delete"),    1 },
1463   { "dv", NL ("/"),         2 },
1464   { "eO", NL ("^="),        2 },
1465   { "eo", NL ("^"),         2 },
1466   { "eq", NL ("=="),        2 },
1467   { "ge", NL (">="),        2 },
1468   { "gt", NL (">"),         2 },
1469   { "ix", NL ("[]"),        2 },
1470   { "lS", NL ("<<="),       2 },
1471   { "le", NL ("<="),        2 },
1472   { "ls", NL ("<<"),        2 },
1473   { "lt", NL ("<"),         2 },
1474   { "mI", NL ("-="),        2 },
1475   { "mL", NL ("*="),        2 },
1476   { "mi", NL ("-"),         2 },
1477   { "ml", NL ("*"),         2 },
1478   { "mm", NL ("--"),        1 },
1479   { "na", NL ("new[]"),     1 },
1480   { "ne", NL ("!="),        2 },
1481   { "ng", NL ("-"),         1 },
1482   { "nt", NL ("!"),         1 },
1483   { "nw", NL ("new"),       1 },
1484   { "oR", NL ("|="),        2 },
1485   { "oo", NL ("||"),        2 },
1486   { "or", NL ("|"),         2 },
1487   { "pL", NL ("+="),        2 },
1488   { "pl", NL ("+"),         2 },
1489   { "pm", NL ("->*"),       2 },
1490   { "pp", NL ("++"),        1 },
1491   { "ps", NL ("+"),         1 },
1492   { "pt", NL ("->"),        2 },
1493   { "qu", NL ("?"),         3 },
1494   { "rM", NL ("%="),        2 },
1495   { "rS", NL (">>="),       2 },
1496   { "rm", NL ("%"),         2 },
1497   { "rs", NL (">>"),        2 },
1498   { "st", NL ("sizeof "),   1 },
1499   { "sz", NL ("sizeof "),   1 }
1500 };
1501
1502 static struct d_comp *
1503 d_operator_name (di)
1504      struct d_info *di;
1505 {
1506   char c1;
1507   char c2;
1508
1509   c1 = d_next_char (di);
1510   c2 = d_next_char (di);
1511   if (c1 == 'v' && IS_DIGIT (c2))
1512     return d_make_extended_operator (di, c2 - '0', d_source_name (di));
1513   else if (c1 == 'c' && c2 == 'v')
1514     return d_make_comp (di, D_COMP_CAST, d_type (di), NULL);
1515   else
1516     {
1517       int low = 0;
1518       int high = sizeof (d_operators) / sizeof (d_operators[0]);
1519
1520       while (1)
1521         {
1522           int i;
1523           const struct d_operator_info *p;
1524
1525           i = low + (high - low) / 2;
1526           p = d_operators + i;
1527
1528           if (c1 == p->code[0] && c2 == p->code[1])
1529             return d_make_operator (di, p);
1530
1531           if (c1 < p->code[0] || (c1 == p->code[0] && c2 < p->code[1]))
1532             high = i;
1533           else
1534             low = i + 1;
1535           if (low == high)
1536             return NULL;
1537         }
1538     }
1539 }
1540
1541 /* <special-name> ::= TV <type>
1542                   ::= TT <type>
1543                   ::= TI <type>
1544                   ::= TS <type>
1545                   ::= GV <(object) name>
1546                   ::= T <call-offset> <(base) encoding>
1547                   ::= Tc <call-offset> <call-offset> <(base) encoding>
1548    Also g++ extensions:
1549                   ::= TC <type> <(offset) number> _ <(base) type>
1550                   ::= TF <type>
1551                   ::= TJ <type>
1552                   ::= GR <name>
1553 */
1554
1555 static struct d_comp *
1556 d_special_name (di)
1557      struct d_info *di;
1558 {
1559   char c;
1560
1561   di->expansion += 20;
1562   c = d_next_char (di);
1563   if (c == 'T')
1564     {
1565       switch (d_next_char (di))
1566         {
1567         case 'V':
1568           di->expansion -= 5;
1569           return d_make_comp (di, D_COMP_VTABLE, d_type (di), NULL);
1570         case 'T':
1571           di->expansion -= 10;
1572           return d_make_comp (di, D_COMP_VTT, d_type (di), NULL);
1573         case 'I':
1574           return d_make_comp (di, D_COMP_TYPEINFO, d_type (di), NULL);
1575         case 'S':
1576           return d_make_comp (di, D_COMP_TYPEINFO_NAME, d_type (di), NULL);
1577
1578         case 'h':
1579           if (! d_call_offset (di, 'h'))
1580             return NULL;
1581           return d_make_comp (di, D_COMP_THUNK, d_encoding (di, 0), NULL);
1582
1583         case 'v':
1584           if (! d_call_offset (di, 'v'))
1585             return NULL;
1586           return d_make_comp (di, D_COMP_VIRTUAL_THUNK, d_encoding (di, 0),
1587                               NULL);
1588
1589         case 'c':
1590           if (! d_call_offset (di, '\0'))
1591             return NULL;
1592           if (! d_call_offset (di, '\0'))
1593             return NULL;
1594           return d_make_comp (di, D_COMP_COVARIANT_THUNK, d_encoding (di, 0),
1595                               NULL);
1596
1597         case 'C':
1598           {
1599             struct d_comp *derived_type;
1600             long offset;
1601             struct d_comp *base_type;
1602
1603             derived_type = d_type (di);
1604             offset = d_number (di);
1605             if (offset < 0)
1606               return NULL;
1607             if (d_next_char (di) != '_')
1608               return NULL;
1609             base_type = d_type (di);
1610             /* We don't display the offset.  FIXME: We should display
1611                it in verbose mode.  */
1612             di->expansion += 5;
1613             return d_make_comp (di, D_COMP_CONSTRUCTION_VTABLE, base_type,
1614                                 derived_type);
1615           }
1616
1617         case 'F':
1618           return d_make_comp (di, D_COMP_TYPEINFO_FN, d_type (di), NULL);
1619         case 'J':
1620           return d_make_comp (di, D_COMP_JAVA_CLASS, d_type (di), NULL);
1621
1622         default:
1623           return NULL;
1624         }
1625     }
1626   else if (c == 'G')
1627     {
1628       switch (d_next_char (di))
1629         {
1630         case 'V':
1631           return d_make_comp (di, D_COMP_GUARD, d_name (di), NULL);
1632
1633         case 'R':
1634           return d_make_comp (di, D_COMP_REFTEMP, d_name (di), NULL);
1635
1636         default:
1637           return NULL;
1638         }
1639     }
1640   else
1641     return NULL;
1642 }
1643
1644 /* <call-offset> ::= h <nv-offset> _
1645                  ::= v <v-offset> _
1646
1647    <nv-offset> ::= <(offset) number>
1648
1649    <v-offset> ::= <(offset) number> _ <(virtual offset) number>
1650
1651    The C parameter, if not '\0', is a character we just read which is
1652    the start of the <call-offset>.
1653
1654    We don't display the offset information anywhere.  FIXME: We should
1655    display it in verbose mode.  */
1656
1657 static int
1658 d_call_offset (di, c)
1659      struct d_info *di;
1660      int c;
1661 {
1662   long offset;
1663   long virtual_offset;
1664
1665   if (c == '\0')
1666     c = d_next_char (di);
1667
1668   if (c == 'h')
1669     offset = d_number (di);
1670   else if (c == 'v')
1671     {
1672       offset = d_number (di);
1673       if (d_next_char (di) != '_')
1674         return 0;
1675       virtual_offset = d_number (di);
1676     }
1677   else
1678     return 0;
1679
1680   if (d_next_char (di) != '_')
1681     return 0;
1682
1683   return 1;
1684 }
1685
1686 /* <ctor-dtor-name> ::= C1
1687                     ::= C2
1688                     ::= C3
1689                     ::= D0
1690                     ::= D1
1691                     ::= D2
1692 */
1693
1694 static struct d_comp *
1695 d_ctor_dtor_name (di)
1696      struct d_info *di;
1697 {
1698   if (di->last_name != NULL)
1699     {
1700       if (di->last_name->type == D_COMP_NAME)
1701         di->expansion += di->last_name->u.s_name.len;
1702       else if (di->last_name->type == D_COMP_SUB_STD)
1703         di->expansion += di->last_name->u.s_string.len;
1704     }
1705   switch (d_next_char (di))
1706     {
1707     case 'C':
1708       {
1709         enum gnu_v3_ctor_kinds kind;
1710
1711         switch (d_next_char (di))
1712           {
1713           case '1':
1714             kind = gnu_v3_complete_object_ctor;
1715             break;
1716           case '2':
1717             kind = gnu_v3_base_object_ctor;
1718             break;
1719           case '3':
1720             kind = gnu_v3_complete_object_allocating_ctor;
1721             break;
1722           default:
1723             return NULL;
1724           }
1725         return d_make_ctor (di, kind, di->last_name);
1726       }
1727
1728     case 'D':
1729       {
1730         enum gnu_v3_dtor_kinds kind;
1731
1732         switch (d_next_char (di))
1733           {
1734           case '0':
1735             kind = gnu_v3_deleting_dtor;
1736             break;
1737           case '1':
1738             kind = gnu_v3_complete_object_dtor;
1739             break;
1740           case '2':
1741             kind = gnu_v3_base_object_dtor;
1742             break;
1743           default:
1744             return NULL;
1745           }
1746         return d_make_dtor (di, kind, di->last_name);
1747       }
1748
1749     default:
1750       return NULL;
1751     }
1752 }
1753
1754 /* <type> ::= <builtin-type>
1755           ::= <function-type>
1756           ::= <class-enum-type>
1757           ::= <array-type>
1758           ::= <pointer-to-member-type>
1759           ::= <template-param>
1760           ::= <template-template-param> <template-args>
1761           ::= <substitution>
1762           ::= <CV-qualifiers> <type>
1763           ::= P <type>
1764           ::= R <type>
1765           ::= C <type>
1766           ::= G <type>
1767           ::= U <source-name> <type>
1768
1769    <builtin-type> ::= various one letter codes
1770                   ::= u <source-name>
1771 */
1772
1773 static const struct d_builtin_type_info d_builtin_types[26] =
1774 {
1775   /* a */ { NL ("signed char"), NL ("signed char"),     D_PRINT_INT },
1776   /* b */ { NL ("bool"),        NL ("boolean"),         D_PRINT_BOOL },
1777   /* c */ { NL ("char"),        NL ("byte"),            D_PRINT_INT },
1778   /* d */ { NL ("double"),      NL ("double"),          D_PRINT_DEFAULT },
1779   /* e */ { NL ("long double"), NL ("long double"),     D_PRINT_DEFAULT },
1780   /* f */ { NL ("float"),       NL ("float"),           D_PRINT_DEFAULT },
1781   /* g */ { NL ("__float128"),  NL ("__float128"),      D_PRINT_DEFAULT },
1782   /* h */ { NL ("unsigned char"), NL ("unsigned char"), D_PRINT_INT },
1783   /* i */ { NL ("int"),         NL ("int"),             D_PRINT_INT },
1784   /* j */ { NL ("unsigned int"), NL ("unsigned"),       D_PRINT_INT },
1785   /* k */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1786   /* l */ { NL ("long"),        NL ("long"),            D_PRINT_LONG },
1787   /* m */ { NL ("unsigned long"), NL ("unsigned long"), D_PRINT_LONG },
1788   /* n */ { NL ("__int128"),    NL ("__int128"),        D_PRINT_DEFAULT },
1789   /* o */ { NL ("unsigned __int128"), NL ("unsigned __int128"), D_PRINT_DEFAULT },
1790   /* p */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1791   /* q */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1792   /* r */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1793   /* s */ { NL ("short"),       NL ("short"),           D_PRINT_INT },
1794   /* t */ { NL ("unsigned short"), NL ("unsigned short"), D_PRINT_INT },
1795   /* u */ { NULL, 0,            NULL, 0,                D_PRINT_DEFAULT },
1796   /* v */ { NL ("void"),        NL ("void"),            D_PRINT_VOID },
1797   /* w */ { NL ("wchar_t"),     NL ("char"),            D_PRINT_INT },
1798   /* x */ { NL ("long long"),   NL ("long"),            D_PRINT_DEFAULT },
1799   /* y */ { NL ("unsigned long long"), NL ("unsigned long long"), D_PRINT_DEFAULT },
1800   /* z */ { NL ("..."),         NL ("..."),             D_PRINT_DEFAULT },
1801 };
1802
1803 static struct d_comp *
1804 d_type (di)
1805      struct d_info *di;
1806 {
1807   char peek;
1808   struct d_comp *ret;
1809   int can_subst;
1810
1811   /* The ABI specifies that when CV-qualifiers are used, the base type
1812      is substitutable, and the fully qualified type is substitutable,
1813      but the base type with a strict subset of the CV-qualifiers is
1814      not substitutable.  The natural recursive implementation of the
1815      CV-qualifiers would cause subsets to be substitutable, so instead
1816      we pull them all off now.
1817
1818      FIXME: The ABI says that order-insensitive vendor qualifiers
1819      should be handled in the same way, but we have no way to tell
1820      which vendor qualifiers are order-insensitive and which are
1821      order-sensitive.  So we just assume that they are all
1822      order-sensitive.  g++ 3.4 supports only one vendor qualifier,
1823      __vector, and it treats it as order-sensitive when mangling
1824      names.  */
1825
1826   peek = d_peek_char (di);
1827   if (peek == 'r' || peek == 'V' || peek == 'K')
1828     {
1829       struct d_comp **pret;
1830
1831       pret = d_cv_qualifiers (di, &ret, 0);
1832       if (pret == NULL)
1833         return NULL;
1834       *pret = d_type (di);
1835       if (! d_add_substitution (di, ret))
1836         return NULL;
1837       return ret;
1838     }
1839
1840   can_subst = 1;
1841
1842   switch (peek)
1843     {
1844     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
1845     case 'h': case 'i': case 'j':           case 'l': case 'm': case 'n':
1846     case 'o':                               case 's': case 't':
1847     case 'v': case 'w': case 'x': case 'y': case 'z':
1848       ret = d_make_builtin_type (di, &d_builtin_types[peek - 'a']);
1849       di->expansion += ret->u.s_builtin.type->len;
1850       can_subst = 0;
1851       d_advance (di, 1);
1852       break;
1853
1854     case 'u':
1855       d_advance (di, 1);
1856       ret = d_make_comp (di, D_COMP_VENDOR_TYPE, d_source_name (di), NULL);
1857       break;
1858
1859     case 'F':
1860       ret = d_function_type (di);
1861       break;
1862
1863     case '0': case '1': case '2': case '3': case '4':
1864     case '5': case '6': case '7': case '8': case '9':
1865     case 'N':
1866     case 'Z':
1867       ret = d_class_enum_type (di);
1868       break;
1869
1870     case 'A':
1871       ret = d_array_type (di);
1872       break;
1873
1874     case 'M':
1875       ret = d_pointer_to_member_type (di);
1876       break;
1877
1878     case 'T':
1879       ret = d_template_param (di);
1880       if (d_peek_char (di) == 'I')
1881         {
1882           /* This is <template-template-param> <template-args>.  The
1883              <template-template-param> part is a substitution
1884              candidate.  */
1885           if (! d_add_substitution (di, ret))
1886             return NULL;
1887           ret = d_make_comp (di, D_COMP_TEMPLATE, ret, d_template_args (di));
1888         }
1889       break;
1890
1891     case 'S':
1892       /* If this is a special substitution, then it is the start of
1893          <class-enum-type>.  */
1894       {
1895         char peek_next;
1896
1897         peek_next = d_peek_next_char (di);
1898         if (IS_DIGIT (peek_next)
1899             || peek_next == '_'
1900             || IS_UPPER (peek_next))
1901           {
1902             ret = d_substitution (di, 0);
1903             /* The substituted name may have been a template name and
1904                may be followed by tepmlate args.  */
1905             if (d_peek_char (di) == 'I')
1906               ret = d_make_comp (di, D_COMP_TEMPLATE, ret,
1907                                  d_template_args (di));
1908             else
1909               can_subst = 0;
1910           }
1911         else
1912           {
1913             ret = d_class_enum_type (di);
1914             /* If the substitution was a complete type, then it is not
1915                a new substitution candidate.  However, if the
1916                substitution was followed by template arguments, then
1917                the whole thing is a substitution candidate.  */
1918             if (ret != NULL && ret->type == D_COMP_SUB_STD)
1919               can_subst = 0;
1920           }
1921       }
1922       break;
1923
1924     case 'P':
1925       d_advance (di, 1);
1926       ret = d_make_comp (di, D_COMP_POINTER, d_type (di), NULL);
1927       break;
1928
1929     case 'R':
1930       d_advance (di, 1);
1931       ret = d_make_comp (di, D_COMP_REFERENCE, d_type (di), NULL);
1932       break;
1933
1934     case 'C':
1935       d_advance (di, 1);
1936       ret = d_make_comp (di, D_COMP_COMPLEX, d_type (di), NULL);
1937       break;
1938
1939     case 'G':
1940       d_advance (di, 1);
1941       ret = d_make_comp (di, D_COMP_IMAGINARY, d_type (di), NULL);
1942       break;
1943
1944     case 'U':
1945       d_advance (di, 1);
1946       ret = d_source_name (di);
1947       ret = d_make_comp (di, D_COMP_VENDOR_TYPE_QUAL, d_type (di), ret);
1948       break;
1949
1950     default:
1951       return NULL;
1952     }
1953
1954   if (can_subst)
1955     {
1956       if (! d_add_substitution (di, ret))
1957         return NULL;
1958     }
1959
1960   return ret;
1961 }
1962
1963 /* <CV-qualifiers> ::= [r] [V] [K]  */
1964
1965 static struct d_comp **
1966 d_cv_qualifiers (di, pret, member_fn)
1967      struct d_info *di;
1968      struct d_comp **pret;
1969      int member_fn;
1970 {
1971   char peek;
1972
1973   peek = d_peek_char (di);
1974   while (peek == 'r' || peek == 'V' || peek == 'K')
1975     {
1976       enum d_comp_type t;
1977
1978       d_advance (di, 1);
1979       if (peek == 'r')
1980         {
1981           t = member_fn ? D_COMP_RESTRICT_THIS : D_COMP_RESTRICT;
1982           di->expansion += sizeof "restrict";
1983         }
1984       else if (peek == 'V')
1985         {
1986           t = member_fn ? D_COMP_VOLATILE_THIS : D_COMP_VOLATILE;
1987           di->expansion += sizeof "volatile";
1988         }
1989       else
1990         {
1991           t = member_fn ? D_COMP_CONST_THIS : D_COMP_CONST;
1992           di->expansion += sizeof "const";
1993         }
1994
1995       *pret = d_make_comp (di, t, NULL, NULL);
1996       if (*pret == NULL)
1997         return NULL;
1998       pret = &d_left (*pret);
1999
2000       peek = d_peek_char (di);
2001     }
2002
2003   return pret;
2004 }
2005
2006 /* <function-type> ::= F [Y] <bare-function-type> E  */
2007
2008 static struct d_comp *
2009 d_function_type (di)
2010      struct d_info *di;
2011 {
2012   struct d_comp *ret;
2013
2014   if (d_next_char (di) != 'F')
2015     return NULL;
2016   if (d_peek_char (di) == 'Y')
2017     {
2018       /* Function has C linkage.  We don't print this information.
2019          FIXME: We should print it in verbose mode.  */
2020       d_advance (di, 1);
2021     }
2022   ret = d_bare_function_type (di, 1);
2023   if (d_next_char (di) != 'E')
2024     return NULL;
2025   return ret;
2026 }
2027
2028 /* <bare-function-type> ::= <type>+  */
2029
2030 static struct d_comp *
2031 d_bare_function_type (di, has_return_type)
2032      struct d_info *di;
2033      int has_return_type;
2034 {
2035   struct d_comp *return_type;
2036   struct d_comp *tl;
2037   struct d_comp **ptl;
2038
2039   return_type = NULL;
2040   tl = NULL;
2041   ptl = &tl;
2042   while (1)
2043     {
2044       char peek;
2045       struct d_comp *type;
2046
2047       peek = d_peek_char (di);
2048       if (peek == '\0' || peek == 'E')
2049         break;
2050       type = d_type (di);
2051       if (type == NULL)
2052         return NULL;
2053       if (has_return_type)
2054         {
2055           return_type = type;
2056           has_return_type = 0;
2057         }
2058       else
2059         {
2060           *ptl = d_make_comp (di, D_COMP_ARGLIST, type, NULL);
2061           if (*ptl == NULL)
2062             return NULL;
2063           ptl = &d_right (*ptl);
2064         }
2065     }
2066
2067   /* There should be at least one parameter type besides the optional
2068      return type.  A function which takes no arguments will have a
2069      single parameter type void.  */
2070   if (tl == NULL)
2071     return NULL;
2072
2073   /* If we have a single parameter type void, omit it.  */
2074   if (d_right (tl) == NULL
2075       && d_left (tl)->type == D_COMP_BUILTIN_TYPE
2076       && d_left (tl)->u.s_builtin.type->print == D_PRINT_VOID)
2077     {
2078       di->expansion -= d_left (tl)->u.s_builtin.type->len;
2079       tl = NULL;
2080     }
2081
2082   return d_make_comp (di, D_COMP_FUNCTION_TYPE, return_type, tl);
2083 }
2084
2085 /* <class-enum-type> ::= <name>  */
2086
2087 static struct d_comp *
2088 d_class_enum_type (di)
2089      struct d_info *di;
2090 {
2091   return d_name (di);
2092 }
2093
2094 /* <array-type> ::= A <(positive dimension) number> _ <(element) type>
2095                 ::= A [<(dimension) expression>] _ <(element) type>
2096 */
2097
2098 static struct d_comp *
2099 d_array_type (di)
2100      struct d_info *di;
2101 {
2102   char peek;
2103   struct d_comp *dim;
2104
2105   if (d_next_char (di) != 'A')
2106     return NULL;
2107
2108   peek = d_peek_char (di);
2109   if (peek == '_')
2110     dim = NULL;
2111   else if (IS_DIGIT (peek))
2112     {
2113       const char *s;
2114
2115       s = d_str (di);
2116       do
2117         {
2118           d_advance (di, 1);
2119           peek = d_peek_char (di);
2120         }
2121       while (IS_DIGIT (peek));
2122       dim = d_make_name (di, s, d_str (di) - s);
2123       if (dim == NULL)
2124         return NULL;
2125     }
2126   else
2127     {
2128       dim = d_expression (di);
2129       if (dim == NULL)
2130         return NULL;
2131     }
2132
2133   if (d_next_char (di) != '_')
2134     return NULL;
2135
2136   return d_make_comp (di, D_COMP_ARRAY_TYPE, dim, d_type (di));
2137 }
2138
2139 /* <pointer-to-member-type> ::= M <(class) type> <(member) type>  */
2140
2141 static struct d_comp *
2142 d_pointer_to_member_type (di)
2143      struct d_info *di;
2144 {
2145   struct d_comp *cl;
2146   struct d_comp *mem;
2147   struct d_comp **pmem;
2148
2149   if (d_next_char (di) != 'M')
2150     return NULL;
2151
2152   cl = d_type (di);
2153
2154   /* The ABI specifies that any type can be a substitution source, and
2155      that M is followed by two types, and that when a CV-qualified
2156      type is seen both the base type and the CV-qualified types are
2157      substitution sources.  The ABI also specifies that for a pointer
2158      to a CV-qualified member function, the qualifiers are attached to
2159      the second type.  Given the grammar, a plain reading of the ABI
2160      suggests that both the CV-qualified member function and the
2161      non-qualified member function are substitution sources.  However,
2162      g++ does not work that way.  g++ treats only the CV-qualified
2163      member function as a substitution source.  FIXME.  So to work
2164      with g++, we need to pull off the CV-qualifiers here, in order to
2165      avoid calling add_substitution() in d_type().  */
2166
2167   pmem = d_cv_qualifiers (di, &mem, 1);
2168   if (pmem == NULL)
2169     return NULL;
2170   *pmem = d_type (di);
2171
2172   return d_make_comp (di, D_COMP_PTRMEM_TYPE, cl, mem);
2173 }
2174
2175 /* <template-param> ::= T_
2176                     ::= T <(parameter-2 non-negative) number> _
2177 */
2178
2179 static struct d_comp *
2180 d_template_param (di)
2181      struct d_info *di;
2182 {
2183   long param;
2184
2185   if (d_next_char (di) != 'T')
2186     return NULL;
2187
2188   if (d_peek_char (di) == '_')
2189     param = 0;
2190   else
2191     {
2192       param = d_number (di);
2193       if (param < 0)
2194         return NULL;
2195       param += 1;
2196     }
2197
2198   if (d_next_char (di) != '_')
2199     return NULL;
2200
2201   ++di->did_subs;
2202
2203   return d_make_template_param (di, param);
2204 }
2205
2206 /* <template-args> ::= I <template-arg>+ E  */
2207
2208 static struct d_comp *
2209 d_template_args (di)
2210      struct d_info *di;
2211 {
2212   struct d_comp *hold_last_name;
2213   struct d_comp *al;
2214   struct d_comp **pal;
2215
2216   /* Preserve the last name we saw--don't let the template arguments
2217      clobber it, as that would give us the wrong name for a subsequent
2218      constructor or destructor.  */
2219   hold_last_name = di->last_name;
2220
2221   if (d_next_char (di) != 'I')
2222     return NULL;
2223
2224   al = NULL;
2225   pal = &al;
2226   while (1)
2227     {
2228       struct d_comp *a;
2229
2230       a = d_template_arg (di);
2231       if (a == NULL)
2232         return NULL;
2233
2234       *pal = d_make_comp (di, D_COMP_TEMPLATE_ARGLIST, a, NULL);
2235       if (*pal == NULL)
2236         return NULL;
2237       pal = &d_right (*pal);
2238
2239       if (d_peek_char (di) == 'E')
2240         {
2241           d_advance (di, 1);
2242           break;
2243         }
2244     }
2245
2246   di->last_name = hold_last_name;
2247
2248   return al;
2249 }
2250
2251 /* <template-arg> ::= <type>
2252                   ::= X <expression> E
2253                   ::= <expr-primary>
2254 */
2255
2256 static struct d_comp *
2257 d_template_arg (di)
2258      struct d_info *di;
2259 {
2260   struct d_comp *ret;
2261
2262   switch (d_peek_char (di))
2263     {
2264     case 'X':
2265       d_advance (di, 1);
2266       ret = d_expression (di);
2267       if (d_next_char (di) != 'E')
2268         return NULL;
2269       return ret;
2270
2271     case 'L':
2272       return d_expr_primary (di);
2273
2274     default:
2275       return d_type (di);
2276     }
2277 }
2278
2279 /* <expression> ::= <(unary) operator-name> <expression>
2280                 ::= <(binary) operator-name> <expression> <expression>
2281                 ::= <(trinary) operator-name> <expression> <expression> <expression>
2282                 ::= st <type>
2283                 ::= <template-param>
2284                 ::= sr <type> <unqualified-name>
2285                 ::= sr <type> <unqualified-name> <template-args>
2286                 ::= <expr-primary>
2287 */
2288
2289 static struct d_comp *
2290 d_expression (di)
2291      struct d_info *di;
2292 {
2293   char peek;
2294
2295   peek = d_peek_char (di);
2296   if (peek == 'L')
2297     return d_expr_primary (di);
2298   else if (peek == 'T')
2299     return d_template_param (di);
2300   else if (peek == 's' && d_peek_next_char (di) == 'r')
2301     {
2302       struct d_comp *type;
2303       struct d_comp *name;
2304
2305       d_advance (di, 2);
2306       type = d_type (di);
2307       name = d_unqualified_name (di);
2308       if (d_peek_char (di) != 'I')
2309         return d_make_comp (di, D_COMP_QUAL_NAME, type, name);
2310       else
2311         return d_make_comp (di, D_COMP_QUAL_NAME, type,
2312                             d_make_comp (di, D_COMP_TEMPLATE, name,
2313                                          d_template_args (di)));
2314     }
2315   else
2316     {
2317       struct d_comp *op;
2318       int args;
2319
2320       op = d_operator_name (di);
2321       if (op == NULL)
2322         return NULL;
2323
2324       if (op->type == D_COMP_OPERATOR)
2325         di->expansion += op->u.s_operator.op->len - 2;
2326
2327       if (op->type == D_COMP_OPERATOR
2328           && strcmp (op->u.s_operator.op->code, "st") == 0)
2329         return d_make_comp (di, D_COMP_UNARY, op, d_type (di));
2330
2331       switch (op->type)
2332         {
2333         default:
2334           return NULL;
2335         case D_COMP_OPERATOR:
2336           args = op->u.s_operator.op->args;
2337           break;
2338         case D_COMP_EXTENDED_OPERATOR:
2339           args = op->u.s_extended_operator.args;
2340           break;
2341         case D_COMP_CAST:
2342           args = 1;
2343           break;
2344         }
2345
2346       switch (args)
2347         {
2348         case 1:
2349           return d_make_comp (di, D_COMP_UNARY, op, d_expression (di));
2350         case 2:
2351           {
2352             struct d_comp *left;
2353
2354             left = d_expression (di);
2355             return d_make_comp (di, D_COMP_BINARY, op,
2356                                 d_make_comp (di, D_COMP_BINARY_ARGS, left,
2357                                              d_expression (di)));
2358           }
2359         case 3:
2360           {
2361             struct d_comp *first;
2362             struct d_comp *second;
2363
2364             first = d_expression (di);
2365             second = d_expression (di);
2366             return d_make_comp (di, D_COMP_TRINARY, op,
2367                                 d_make_comp (di, D_COMP_TRINARY_ARG1, first,
2368                                              d_make_comp (di,
2369                                                           D_COMP_TRINARY_ARG2,
2370                                                           second,
2371                                                           d_expression (di))));
2372           }
2373         default:
2374           return NULL;
2375         }
2376     }
2377 }
2378
2379 /* <expr-primary> ::= L <type> <(value) number> E
2380                   ::= L <type> <(value) float> E
2381                   ::= L <mangled-name> E
2382 */
2383
2384 static struct d_comp *
2385 d_expr_primary (di)
2386      struct d_info *di;
2387 {
2388   struct d_comp *ret;
2389
2390   if (d_next_char (di) != 'L')
2391     return NULL;
2392   if (d_peek_char (di) == '_')
2393     ret = d_mangled_name (di, 0);
2394   else
2395     {
2396       struct d_comp *type;
2397       enum d_comp_type t;
2398       const char *s;
2399
2400       type = d_type (di);
2401
2402       /* If we have a type we know how to print, we aren't going to
2403          print the type name itself.  */
2404       if (type->type == D_COMP_BUILTIN_TYPE
2405           && type->u.s_builtin.type->print != D_PRINT_DEFAULT)
2406         di->expansion -= type->u.s_builtin.type->len;
2407
2408       /* Rather than try to interpret the literal value, we just
2409          collect it as a string.  Note that it's possible to have a
2410          floating point literal here.  The ABI specifies that the
2411          format of such literals is machine independent.  That's fine,
2412          but what's not fine is that versions of g++ up to 3.2 with
2413          -fabi-version=1 used upper case letters in the hex constant,
2414          and dumped out gcc's internal representation.  That makes it
2415          hard to tell where the constant ends, and hard to dump the
2416          constant in any readable form anyhow.  We don't attempt to
2417          handle these cases.  */
2418
2419       t = D_COMP_LITERAL;
2420       if (d_peek_char (di) == 'n')
2421         {
2422           t = D_COMP_LITERAL_NEG;
2423           d_advance (di, 1);
2424         }
2425       s = d_str (di);
2426       while (d_peek_char (di) != 'E')
2427         d_advance (di, 1);
2428       ret = d_make_comp (di, t, type, d_make_name (di, s, d_str (di) - s));
2429     }
2430   if (d_next_char (di) != 'E')
2431     return NULL;
2432   return ret;
2433 }
2434
2435 /* <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
2436                 ::= Z <(function) encoding> E s [<discriminator>]
2437 */
2438
2439 static struct d_comp *
2440 d_local_name (di)
2441      struct d_info *di;
2442 {
2443   struct d_comp *function;
2444
2445   if (d_next_char (di) != 'Z')
2446     return NULL;
2447
2448   function = d_encoding (di, 0);
2449
2450   if (d_next_char (di) != 'E')
2451     return NULL;
2452
2453   if (d_peek_char (di) == 's')
2454     {
2455       d_advance (di, 1);
2456       if (! d_discriminator (di))
2457         return NULL;
2458       return d_make_comp (di, D_COMP_LOCAL_NAME, function,
2459                           d_make_name (di, "string literal",
2460                                        sizeof "string literal" - 1));
2461     }
2462   else
2463     {
2464       struct d_comp *name;
2465
2466       name = d_name (di);
2467       if (! d_discriminator (di))
2468         return NULL;
2469       return d_make_comp (di, D_COMP_LOCAL_NAME, function, name);
2470     }
2471 }
2472
2473 /* <discriminator> ::= _ <(non-negative) number>
2474
2475    We demangle the discriminator, but we don't print it out.  FIXME:
2476    We should print it out in verbose mode.  */
2477
2478 static int
2479 d_discriminator (di)
2480      struct d_info *di;
2481 {
2482   long discrim;
2483
2484   if (d_peek_char (di) != '_')
2485     return 1;
2486   d_advance (di, 1);
2487   discrim = d_number (di);
2488   if (discrim < 0)
2489     return 0;
2490   return 1;
2491 }
2492
2493 /* Add a new substitution.  */
2494
2495 static int
2496 d_add_substitution (di, dc)
2497      struct d_info *di;
2498      struct d_comp *dc;
2499 {
2500   if (dc == NULL)
2501     return 0;
2502   if (di->next_sub >= di->num_subs)
2503     return 0;
2504   di->subs[di->next_sub] = dc;
2505   ++di->next_sub;
2506   return 1;
2507 }
2508
2509 /* <substitution> ::= S <seq-id> _
2510                   ::= S_
2511                   ::= St
2512                   ::= Sa
2513                   ::= Sb
2514                   ::= Ss
2515                   ::= Si
2516                   ::= So
2517                   ::= Sd
2518
2519    If PREFIX is non-zero, then this type is being used as a prefix in
2520    a qualified name.  In this case, for the standard substitutions, we
2521    need to check whether we are being used as a prefix for a
2522    constructor or destructor, and return a full template name.
2523    Otherwise we will get something like std::iostream::~iostream()
2524    which does not correspond particularly well to any function which
2525    actually appears in the source.
2526 */
2527
2528 static const struct d_standard_sub_info standard_subs[] =
2529 {
2530   { 't', NL ("std"),
2531     NL ("std"),
2532     NULL, 0 },
2533   { 'a', NL ("std::allocator"),
2534     NL ("std::allocator"),
2535     NL ("allocator") },
2536   { 'b', NL ("std::basic_string"),
2537     NL ("std::basic_string"),
2538     NL ("basic_string") },
2539   { 's', NL ("std::string"),
2540     NL ("std::basic_string<char, std::char_traits<char>, std::allocator<char> >"),
2541     NL ("basic_string") },
2542   { 'i', NL ("std::istream"),
2543     NL ("std::basic_istream<char, std::char_traits<char> >"),
2544     NL ("basic_istream") },
2545   { 'o', NL ("std::ostream"),
2546     NL ("std::basic_ostream<char, std::char_traits<char> >"),
2547     NL ("basic_ostream") },
2548   { 'd', NL ("std::iostream"),
2549     NL ("std::basic_iostream<char, std::char_traits<char> >"),
2550     NL ("basic_iostream") }
2551 };
2552
2553 static struct d_comp *
2554 d_substitution (di, prefix)
2555      struct d_info *di;
2556      int prefix;
2557 {
2558   char c;
2559
2560   if (d_next_char (di) != 'S')
2561     return NULL;
2562
2563   c = d_next_char (di);
2564   if (c == '_' || IS_DIGIT (c) || IS_UPPER (c))
2565     {
2566       int id;
2567
2568       id = 0;
2569       if (c != '_')
2570         {
2571           do
2572             {
2573               if (IS_DIGIT (c))
2574                 id = id * 36 + c - '0';
2575               else if (IS_UPPER (c))
2576                 id = id * 36 + c - 'A' + 10;
2577               else
2578                 return NULL;
2579               c = d_next_char (di);
2580             }
2581           while (c != '_');
2582
2583           ++id;
2584         }
2585
2586       if (id >= di->next_sub)
2587         return NULL;
2588
2589       ++di->did_subs;
2590
2591       return di->subs[id];
2592     }
2593   else
2594     {
2595       int verbose;
2596       const struct d_standard_sub_info *p;
2597       const struct d_standard_sub_info *pend;
2598
2599       verbose = (di->options & DMGL_VERBOSE) != 0;
2600       if (! verbose && prefix)
2601         {
2602           char peek;
2603
2604           peek = d_peek_char (di);
2605           if (peek == 'C' || peek == 'D')
2606             verbose = 1;
2607         }
2608
2609       pend = (&standard_subs[0]
2610               + sizeof standard_subs / sizeof standard_subs[0]);
2611       for (p = &standard_subs[0]; p < pend; ++p)
2612         {
2613           if (c == p->code)
2614             {
2615               const char *s;
2616               int len;
2617
2618               if (p->set_last_name != NULL)
2619                 di->last_name = d_make_sub (di, p->set_last_name,
2620                                             p->set_last_name_len);
2621               if (verbose)
2622                 {
2623                   s = p->full_expansion;
2624                   len = p->full_len;
2625                 }
2626               else
2627                 {
2628                   s = p->simple_expansion;
2629                   len = p->simple_len;
2630                 }
2631               di->expansion += len;
2632               return d_make_sub (di, s, len);
2633             }
2634         }
2635
2636       return NULL;
2637     }
2638 }
2639
2640 /* Resize the print buffer.  */
2641
2642 static void
2643 d_print_resize (dpi, add)
2644      struct d_print_info *dpi;
2645      size_t add;
2646 {
2647   size_t need;
2648
2649   if (dpi->buf == NULL)
2650     return;
2651   need = dpi->len + add;
2652   while (need > dpi->alc)
2653     {
2654       size_t newalc;
2655       char *newbuf;
2656
2657       newalc = dpi->alc * 2;
2658       newbuf = realloc (dpi->buf, newalc);
2659       if (newbuf == NULL)
2660         {
2661           free (dpi->buf);
2662           dpi->buf = NULL;
2663           dpi->allocation_failure = 1;
2664           return;
2665         }
2666       dpi->buf = newbuf;
2667       dpi->alc = newalc;
2668     }
2669 }
2670
2671 /* Append a character to the print buffer.  */
2672
2673 static void
2674 d_print_append_char (dpi, c)
2675      struct d_print_info *dpi;
2676      int c;
2677 {
2678   if (dpi->buf != NULL)
2679     {
2680       if (dpi->len >= dpi->alc)
2681         {
2682           d_print_resize (dpi, 1);
2683           if (dpi->buf == NULL)
2684             return;
2685         }
2686
2687       dpi->buf[dpi->len] = c;
2688       ++dpi->len;
2689     }
2690 }
2691
2692 /* Append a buffer to the print buffer.  */
2693
2694 static void
2695 d_print_append_buffer (dpi, s, l)
2696      struct d_print_info *dpi;
2697      const char *s;
2698      size_t l;
2699 {
2700   if (dpi->buf != NULL)
2701     {
2702       if (dpi->len + l > dpi->alc)
2703         {
2704           d_print_resize (dpi, l);
2705           if (dpi->buf == NULL)
2706             return;
2707         }
2708
2709       memcpy (dpi->buf + dpi->len, s, l);
2710       dpi->len += l;
2711     }
2712 }
2713
2714 /* Indicate that an error occurred during printing.  */
2715
2716 static void
2717 d_print_error (dpi)
2718      struct d_print_info *dpi;
2719 {
2720   free (dpi->buf);
2721   dpi->buf = NULL;
2722 }
2723
2724 /* Turn components into a human readable string.  OPTIONS is the
2725    options bits passed to the demangler.  DC is the tree to print.
2726    ESTIMATE is a guess at the length of the result.  This returns a
2727    string allocated by malloc, or NULL on error.  On success, this
2728    sets *PALC to the size of the allocated buffer.  On failure, this
2729    sets *PALC to 0 for a bad parse, or to 1 for a memory allocation
2730    failure.  */
2731
2732 static char *
2733 d_print (options, dc, estimate, palc)
2734      int options;
2735      const struct d_comp *dc;
2736      int estimate;
2737      size_t *palc;
2738 {
2739   struct d_print_info dpi;
2740
2741   dpi.options = options;
2742
2743   dpi.alc = estimate + 1;
2744   dpi.buf = malloc (dpi.alc);
2745   if (dpi.buf == NULL)
2746     {
2747       *palc = 1;
2748       return NULL;
2749     }
2750
2751   dpi.len = 0;
2752   dpi.templates = NULL;
2753   dpi.modifiers = NULL;
2754
2755   dpi.allocation_failure = 0;
2756
2757   d_print_comp (&dpi, dc);
2758
2759   d_append_char (&dpi, '\0');
2760
2761   if (dpi.buf != NULL)
2762     *palc = dpi.alc;
2763   else
2764     *palc = dpi.allocation_failure;
2765
2766   return dpi.buf;
2767 }
2768
2769 /* Subroutine to handle components.  */
2770
2771 static void
2772 d_print_comp (dpi, dc)
2773      struct d_print_info *dpi;
2774      const struct d_comp *dc;
2775 {
2776   if (dc == NULL)
2777     {
2778       d_print_error (dpi);
2779       return;
2780     }
2781   if (d_print_saw_error (dpi))
2782     return;
2783
2784   switch (dc->type)
2785     {
2786     case D_COMP_NAME:
2787       if ((dpi->options & DMGL_JAVA) == 0)
2788         d_append_buffer (dpi, dc->u.s_name.s, dc->u.s_name.len);
2789       else
2790         d_print_java_identifier (dpi, dc->u.s_name.s, dc->u.s_name.len);
2791       return;
2792
2793     case D_COMP_QUAL_NAME:
2794     case D_COMP_LOCAL_NAME:
2795       d_print_comp (dpi, d_left (dc));
2796       if ((dpi->options & DMGL_JAVA) == 0)
2797         d_append_string_constant (dpi, "::");
2798       else
2799         d_append_char (dpi, '.');
2800       d_print_comp (dpi, d_right (dc));
2801       return;
2802
2803     case D_COMP_TYPED_NAME:
2804       {
2805         struct d_print_mod *hold_modifiers;
2806         struct d_comp *typed_name;
2807         struct d_print_mod adpm[4];
2808         unsigned int i;
2809         struct d_print_template dpt;
2810
2811         /* Pass the name down to the type so that it can be printed in
2812            the right place for the type.  We also have to pass down
2813            any CV-qualifiers, which apply to the this parameter.  */
2814         hold_modifiers = dpi->modifiers;
2815         i = 0;
2816         typed_name = d_left (dc);
2817         while (typed_name != NULL)
2818           {
2819             if (i >= sizeof adpm / sizeof adpm[0])
2820               {
2821                 d_print_error (dpi);
2822                 return;
2823               }
2824
2825             adpm[i].next = dpi->modifiers;
2826             dpi->modifiers = &adpm[i];
2827             adpm[i].mod = typed_name;
2828             adpm[i].printed = 0;
2829             adpm[i].templates = dpi->templates;
2830             ++i;
2831
2832             if (typed_name->type != D_COMP_RESTRICT_THIS
2833                 && typed_name->type != D_COMP_VOLATILE_THIS
2834                 && typed_name->type != D_COMP_CONST_THIS)
2835               break;
2836
2837             typed_name = d_left (typed_name);
2838           }
2839
2840         /* If typed_name is a template, then it applies to the
2841            function type as well.  */
2842         if (typed_name->type == D_COMP_TEMPLATE)
2843           {
2844             dpt.next = dpi->templates;
2845             dpi->templates = &dpt;
2846             dpt.template = typed_name;
2847           }
2848
2849         /* If typed_name is a D_COMP_LOCAL_NAME, then there may be
2850            CV-qualifiers on its right argument which really apply
2851            here; this happens when parsing a class which is local to a
2852            function.  */
2853         if (typed_name->type == D_COMP_LOCAL_NAME)
2854           {
2855             struct d_comp *local_name;
2856
2857             local_name = d_right (typed_name);
2858             while (local_name->type == D_COMP_RESTRICT_THIS
2859                    || local_name->type == D_COMP_VOLATILE_THIS
2860                    || local_name->type == D_COMP_CONST_THIS)
2861               {
2862                 if (i >= sizeof adpm / sizeof adpm[0])
2863                   {
2864                     d_print_error (dpi);
2865                     return;
2866                   }
2867
2868                 adpm[i] = adpm[i - 1];
2869                 adpm[i].next = &adpm[i - 1];
2870                 dpi->modifiers = &adpm[i];
2871
2872                 adpm[i - 1].mod = local_name;
2873                 adpm[i - 1].printed = 0;
2874                 adpm[i - 1].templates = dpi->templates;
2875                 ++i;
2876
2877                 local_name = d_left (local_name);
2878               }
2879           }
2880
2881         d_print_comp (dpi, d_right (dc));
2882
2883         if (typed_name->type == D_COMP_TEMPLATE)
2884           dpi->templates = dpt.next;
2885
2886         /* If the modifiers didn't get printed by the type, print them
2887            now.  */
2888         while (i > 0)
2889           {
2890             --i;
2891             if (! adpm[i].printed)
2892               {
2893                 d_append_char (dpi, ' ');
2894                 d_print_mod (dpi, adpm[i].mod);
2895               }
2896           }
2897
2898         dpi->modifiers = hold_modifiers;
2899
2900         return;
2901       }
2902
2903     case D_COMP_TEMPLATE:
2904       {
2905         struct d_print_mod *hold_dpm;
2906
2907         /* Don't push modifiers into a template definition.  Doing so
2908            could give the wrong definition for a template argument.
2909            Instead, treat the template essentially as a name.  */
2910
2911         hold_dpm = dpi->modifiers;
2912         dpi->modifiers = NULL;
2913
2914         d_print_comp (dpi, d_left (dc));
2915         if (d_last_char (dpi) == '<')
2916           d_append_char (dpi, ' ');
2917         d_append_char (dpi, '<');
2918         d_print_comp (dpi, d_right (dc));
2919         /* Avoid generating two consecutive '>' characters, to avoid
2920            the C++ syntactic ambiguity.  */
2921         if (d_last_char (dpi) == '>')
2922           d_append_char (dpi, ' ');
2923         d_append_char (dpi, '>');
2924
2925         dpi->modifiers = hold_dpm;
2926
2927         return;
2928       }
2929
2930     case D_COMP_TEMPLATE_PARAM:
2931       {
2932         long i;
2933         struct d_comp *a;
2934         struct d_print_template *hold_dpt;
2935
2936         if (dpi->templates == NULL)
2937           {
2938             d_print_error (dpi);
2939             return;
2940           }
2941         i = dc->u.s_number.number;
2942         for (a = d_right (dpi->templates->template);
2943              a != NULL;
2944              a = d_right (a))
2945           {
2946             if (a->type != D_COMP_TEMPLATE_ARGLIST)
2947               {
2948                 d_print_error (dpi);
2949                 return;
2950               }
2951             if (i <= 0)
2952               break;
2953             --i;
2954           }
2955         if (i != 0 || a == NULL)
2956           {
2957             d_print_error (dpi);
2958             return;
2959           }
2960
2961         /* While processing this parameter, we need to pop the list of
2962            templates.  This is because the template parameter may
2963            itself be a reference to a parameter of an outer
2964            template.  */
2965
2966         hold_dpt = dpi->templates;
2967         dpi->templates = hold_dpt->next;
2968
2969         d_print_comp (dpi, d_left (a));
2970
2971         dpi->templates = hold_dpt;
2972
2973         return;
2974       }
2975
2976     case D_COMP_CTOR:
2977       d_print_comp (dpi, dc->u.s_ctor.name);
2978       return;
2979
2980     case D_COMP_DTOR:
2981       d_append_char (dpi, '~');
2982       d_print_comp (dpi, dc->u.s_dtor.name);
2983       return;
2984
2985     case D_COMP_VTABLE:
2986       d_append_string_constant (dpi, "vtable for ");
2987       d_print_comp (dpi, d_left (dc));
2988       return;
2989
2990     case D_COMP_VTT:
2991       d_append_string_constant (dpi, "VTT for ");
2992       d_print_comp (dpi, d_left (dc));
2993       return;
2994
2995     case D_COMP_CONSTRUCTION_VTABLE:
2996       d_append_string_constant (dpi, "construction vtable for ");
2997       d_print_comp (dpi, d_left (dc));
2998       d_append_string_constant (dpi, "-in-");
2999       d_print_comp (dpi, d_right (dc));
3000       return;
3001
3002     case D_COMP_TYPEINFO:
3003       d_append_string_constant (dpi, "typeinfo for ");
3004       d_print_comp (dpi, d_left (dc));
3005       return;
3006
3007     case D_COMP_TYPEINFO_NAME:
3008       d_append_string_constant (dpi, "typeinfo name for ");
3009       d_print_comp (dpi, d_left (dc));
3010       return;
3011
3012     case D_COMP_TYPEINFO_FN:
3013       d_append_string_constant (dpi, "typeinfo fn for ");
3014       d_print_comp (dpi, d_left (dc));
3015       return;
3016
3017     case D_COMP_THUNK:
3018       d_append_string_constant (dpi, "non-virtual thunk to ");
3019       d_print_comp (dpi, d_left (dc));
3020       return;
3021
3022     case D_COMP_VIRTUAL_THUNK:
3023       d_append_string_constant (dpi, "virtual thunk to ");
3024       d_print_comp (dpi, d_left (dc));
3025       return;
3026
3027     case D_COMP_COVARIANT_THUNK:
3028       d_append_string_constant (dpi, "covariant return thunk to ");
3029       d_print_comp (dpi, d_left (dc));
3030       return;
3031
3032     case D_COMP_JAVA_CLASS:
3033       d_append_string_constant (dpi, "java Class for ");
3034       d_print_comp (dpi, d_left (dc));
3035       return;
3036
3037     case D_COMP_GUARD:
3038       d_append_string_constant (dpi, "guard variable for ");
3039       d_print_comp (dpi, d_left (dc));
3040       return;
3041
3042     case D_COMP_REFTEMP:
3043       d_append_string_constant (dpi, "reference temporary for ");
3044       d_print_comp (dpi, d_left (dc));
3045       return;
3046
3047     case D_COMP_SUB_STD:
3048       d_append_buffer (dpi, dc->u.s_string.string, dc->u.s_string.len);
3049       return;
3050
3051     case D_COMP_RESTRICT:
3052     case D_COMP_VOLATILE:
3053     case D_COMP_CONST:
3054     case D_COMP_RESTRICT_THIS:
3055     case D_COMP_VOLATILE_THIS:
3056     case D_COMP_CONST_THIS:
3057     case D_COMP_VENDOR_TYPE_QUAL:
3058     case D_COMP_POINTER:
3059     case D_COMP_REFERENCE:
3060     case D_COMP_COMPLEX:
3061     case D_COMP_IMAGINARY:
3062       {
3063         /* We keep a list of modifiers on the stack.  */
3064         struct d_print_mod dpm;
3065
3066         dpm.next = dpi->modifiers;
3067         dpi->modifiers = &dpm;
3068         dpm.mod = dc;
3069         dpm.printed = 0;
3070         dpm.templates = dpi->templates;
3071
3072         d_print_comp (dpi, d_left (dc));
3073
3074         /* If the modifier didn't get printed by the type, print it
3075            now.  */
3076         if (! dpm.printed)
3077           d_print_mod (dpi, dc);
3078
3079         dpi->modifiers = dpm.next;
3080
3081         return;
3082       }
3083
3084     case D_COMP_BUILTIN_TYPE:
3085       if ((dpi->options & DMGL_JAVA) == 0)
3086         d_append_buffer (dpi, dc->u.s_builtin.type->name,
3087                          dc->u.s_builtin.type->len);
3088       else
3089         d_append_buffer (dpi, dc->u.s_builtin.type->java_name,
3090                          dc->u.s_builtin.type->java_len);
3091       return;
3092
3093     case D_COMP_VENDOR_TYPE:
3094       d_print_comp (dpi, d_left (dc));
3095       return;
3096
3097     case D_COMP_FUNCTION_TYPE:
3098       {
3099         if (d_left (dc) != NULL)
3100           {
3101             struct d_print_mod dpm;
3102
3103             /* We must pass this type down as a modifier in order to
3104                print it in the right location.  */
3105
3106             dpm.next = dpi->modifiers;
3107             dpi->modifiers = &dpm;
3108             dpm.mod = dc;
3109             dpm.printed = 0;
3110             dpm.templates = dpi->templates;
3111
3112             d_print_comp (dpi, d_left (dc));
3113
3114             dpi->modifiers = dpm.next;
3115
3116             if (dpm.printed)
3117               return;
3118
3119             d_append_char (dpi, ' ');
3120           }
3121
3122         d_print_function_type (dpi, dc, dpi->modifiers);
3123
3124         return;
3125       }
3126
3127     case D_COMP_ARRAY_TYPE:
3128       {
3129         struct d_print_mod dpm;
3130
3131         /* We must pass this type down as a modifier in order to print
3132            multi-dimensional arrays correctly.  */
3133
3134         dpm.next = dpi->modifiers;
3135         dpi->modifiers = &dpm;
3136         dpm.mod = dc;
3137         dpm.printed = 0;
3138         dpm.templates = dpi->templates;
3139
3140         d_print_comp (dpi, d_right (dc));
3141
3142         dpi->modifiers = dpm.next;
3143
3144         if (dpm.printed)
3145           return;
3146
3147         d_print_array_type (dpi, dc, dpi->modifiers);
3148
3149         return;
3150       }
3151
3152     case D_COMP_PTRMEM_TYPE:
3153       {
3154         struct d_print_mod dpm;
3155
3156         dpm.next = dpi->modifiers;
3157         dpi->modifiers = &dpm;
3158         dpm.mod = dc;
3159         dpm.printed = 0;
3160         dpm.templates = dpi->templates;
3161
3162         d_print_comp (dpi, d_right (dc));
3163
3164         /* If the modifier didn't get printed by the type, print it
3165            now.  */
3166         if (! dpm.printed)
3167           {
3168             d_append_char (dpi, ' ');
3169             d_print_comp (dpi, d_left (dc));
3170             d_append_string_constant (dpi, "::*");
3171           }
3172
3173         dpi->modifiers = dpm.next;
3174
3175         return;
3176       }
3177
3178     case D_COMP_ARGLIST:
3179     case D_COMP_TEMPLATE_ARGLIST:
3180       d_print_comp (dpi, d_left (dc));
3181       if (d_right (dc) != NULL)
3182         {
3183           d_append_string_constant (dpi, ", ");
3184           d_print_comp (dpi, d_right (dc));
3185         }
3186       return;
3187
3188     case D_COMP_OPERATOR:
3189       {
3190         char c;
3191
3192         d_append_string_constant (dpi, "operator");
3193         c = dc->u.s_operator.op->name[0];
3194         if (IS_LOWER (c))
3195           d_append_char (dpi, ' ');
3196         d_append_buffer (dpi, dc->u.s_operator.op->name,
3197                          dc->u.s_operator.op->len);
3198         return;
3199       }
3200
3201     case D_COMP_EXTENDED_OPERATOR:
3202       d_append_string_constant (dpi, "operator ");
3203       d_print_comp (dpi, dc->u.s_extended_operator.name);
3204       return;
3205
3206     case D_COMP_CAST:
3207       d_append_string_constant (dpi, "operator ");
3208       d_print_cast (dpi, dc);
3209       return;
3210
3211     case D_COMP_UNARY:
3212       if (d_left (dc)->type != D_COMP_CAST)
3213         d_print_expr_op (dpi, d_left (dc));
3214       else
3215         {
3216           d_append_string_constant (dpi, "((");
3217           d_print_cast (dpi, d_left (dc));
3218           d_append_char (dpi, ')');
3219         }
3220       d_append_char (dpi, '(');
3221       d_print_comp (dpi, d_right (dc));
3222       d_append_char (dpi, ')');
3223       if (d_left (dc)->type == D_COMP_CAST)
3224         d_append_char (dpi, ')');
3225       return;
3226
3227     case D_COMP_BINARY:
3228       if (d_right (dc)->type != D_COMP_BINARY_ARGS)
3229         {
3230           d_print_error (dpi);
3231           return;
3232         }
3233
3234       /* We wrap an expression which uses the greater-than operator in
3235          an extra layer of parens so that it does not get confused
3236          with the '>' which ends the template parameters.  */
3237       if (d_left (dc)->type == D_COMP_OPERATOR
3238           && d_left (dc)->u.s_operator.op->len == 1
3239           && d_left (dc)->u.s_operator.op->name[0] == '>')
3240         d_append_char (dpi, '(');
3241
3242       d_append_char (dpi, '(');
3243       d_print_comp (dpi, d_left (d_right (dc)));
3244       d_append_string_constant (dpi, ") ");
3245       d_print_expr_op (dpi, d_left (dc));
3246       d_append_string_constant (dpi, " (");
3247       d_print_comp (dpi, d_right (d_right (dc)));
3248       d_append_char (dpi, ')');
3249
3250       if (d_left (dc)->type == D_COMP_OPERATOR
3251           && d_left (dc)->u.s_operator.op->len == 1
3252           && d_left (dc)->u.s_operator.op->name[0] == '>')
3253         d_append_char (dpi, ')');
3254
3255       return;
3256
3257     case D_COMP_BINARY_ARGS:
3258       /* We should only see this as part of D_COMP_BINARY.  */
3259       d_print_error (dpi);
3260       return;
3261
3262     case D_COMP_TRINARY:
3263       if (d_right (dc)->type != D_COMP_TRINARY_ARG1
3264           || d_right (d_right (dc))->type != D_COMP_TRINARY_ARG2)
3265         {
3266           d_print_error (dpi);
3267           return;
3268         }
3269       d_append_char (dpi, '(');
3270       d_print_comp (dpi, d_left (d_right (dc)));
3271       d_append_string_constant (dpi, ") ");
3272       d_print_expr_op (dpi, d_left (dc));
3273       d_append_string_constant (dpi, " (");
3274       d_print_comp (dpi, d_left (d_right (d_right (dc))));
3275       d_append_string_constant (dpi, ") : (");
3276       d_print_comp (dpi, d_right (d_right (d_right (dc))));
3277       d_append_char (dpi, ')');
3278       return;
3279
3280     case D_COMP_TRINARY_ARG1:
3281     case D_COMP_TRINARY_ARG2:
3282       /* We should only see these are part of D_COMP_TRINARY.  */
3283       d_print_error (dpi);
3284       return;
3285
3286     case D_COMP_LITERAL:
3287     case D_COMP_LITERAL_NEG:
3288       /* For some builtin types, produce simpler output.  */
3289       if (d_left (dc)->type == D_COMP_BUILTIN_TYPE)
3290         {
3291           switch (d_left (dc)->u.s_builtin.type->print)
3292             {
3293             case D_PRINT_INT:
3294               if (d_right (dc)->type == D_COMP_NAME)
3295                 {
3296                   if (dc->type == D_COMP_LITERAL_NEG)
3297                     d_append_char (dpi, '-');
3298                   d_print_comp (dpi, d_right (dc));
3299                   return;
3300                 }
3301               break;
3302
3303             case D_PRINT_LONG:
3304               if (d_right (dc)->type == D_COMP_NAME)
3305                 {
3306                   if (dc->type == D_COMP_LITERAL_NEG)
3307                     d_append_char (dpi, '-');
3308                   d_print_comp (dpi, d_right (dc));
3309                   d_append_char (dpi, 'l');
3310                   return;
3311                 }
3312               break;
3313
3314             case D_PRINT_BOOL:
3315               if (d_right (dc)->type == D_COMP_NAME
3316                   && d_right (dc)->u.s_name.len == 1
3317                   && dc->type == D_COMP_LITERAL)
3318                 {
3319                   switch (d_right (dc)->u.s_name.s[0])
3320                     {
3321                     case '0':
3322                       d_append_string_constant (dpi, "false");
3323                       return;
3324                     case '1':
3325                       d_append_string_constant (dpi, "true");
3326                       return;
3327                     default:
3328                       break;
3329                     }
3330                 }
3331               break;
3332
3333             default:
3334               break;
3335             }
3336         }
3337
3338       d_append_char (dpi, '(');
3339       d_print_comp (dpi, d_left (dc));
3340       d_append_char (dpi, ')');
3341       if (dc->type == D_COMP_LITERAL_NEG)
3342         d_append_char (dpi, '-');
3343       d_print_comp (dpi, d_right (dc));
3344       return;
3345
3346     default:
3347       d_print_error (dpi);
3348       return;
3349     }
3350 }
3351
3352 /* Print a Java dentifier.  For Java we try to handle encoded extended
3353    Unicode characters.  The C++ ABI doesn't mention Unicode encoding,
3354    so we don't it for C++.  Characters are encoded as
3355    __U<hex-char>+_.  */
3356
3357 static void
3358 d_print_java_identifier (dpi, name, len)
3359      struct d_print_info *dpi;
3360      const char *name;
3361      int len;
3362 {
3363   const char *p;
3364   const char *end;
3365
3366   end = name + len;
3367   for (p = name; p < end; ++p)
3368     {
3369       if (end - p > 3
3370           && p[0] == '_'
3371           && p[1] == '_'
3372           && p[2] == 'U')
3373         {
3374           unsigned long c;
3375           const char *q;
3376
3377           c = 0;
3378           for (q = p + 3; q < end; ++q)
3379             {
3380               int dig;
3381
3382               if (IS_DIGIT (*q))
3383                 dig = *q - '0';
3384               else if (*q >= 'A' && *q <= 'F')
3385                 dig = *q - 'A' + 10;
3386               else if (*q >= 'a' && *q <= 'f')
3387                 dig = *q - 'a' + 10;
3388               else
3389                 break;
3390
3391               c = c * 16 + dig;
3392             }
3393           /* If the Unicode character is larger than 256, we don't try
3394              to deal with it here.  FIXME.  */
3395           if (q < end && *q == '_' && c < 256)
3396             {
3397               d_append_char (dpi, c);
3398               p = q;
3399               continue;
3400             }
3401         }
3402
3403       d_append_char (dpi, *p);
3404     }
3405 }
3406
3407 /* Print a list of modifiers.  SUFFIX is 1 if we are printing
3408    qualifiers on this after printing a function.  */
3409
3410 static void
3411 d_print_mod_list (dpi, mods, suffix)
3412      struct d_print_info *dpi;
3413      struct d_print_mod *mods;
3414      int suffix;
3415 {
3416   struct d_print_template *hold_dpt;
3417
3418   if (mods == NULL || d_print_saw_error (dpi))
3419     return;
3420
3421   if (mods->printed
3422       || (! suffix
3423           && (mods->mod->type == D_COMP_RESTRICT_THIS
3424               || mods->mod->type == D_COMP_VOLATILE_THIS
3425               || mods->mod->type == D_COMP_CONST_THIS)))
3426     {
3427       d_print_mod_list (dpi, mods->next, suffix);
3428       return;
3429     }
3430
3431   mods->printed = 1;
3432
3433   hold_dpt = dpi->templates;
3434   dpi->templates = mods->templates;
3435
3436   if (mods->mod->type == D_COMP_FUNCTION_TYPE)
3437     {
3438       d_print_function_type (dpi, mods->mod, mods->next);
3439       dpi->templates = hold_dpt;
3440       return;
3441     }
3442   else if (mods->mod->type == D_COMP_ARRAY_TYPE)
3443     {
3444       d_print_array_type (dpi, mods->mod, mods->next);
3445       dpi->templates = hold_dpt;
3446       return;
3447     }
3448   else if (mods->mod->type == D_COMP_LOCAL_NAME)
3449     {
3450       struct d_print_mod *hold_modifiers;
3451       struct d_comp *dc;
3452
3453       /* When this is on the modifier stack, we have pulled any
3454          qualifiers off the right argument already.  Otherwise, we
3455          print it as usual, but don't let the left argument see any
3456          modifiers.  */
3457
3458       hold_modifiers = dpi->modifiers;
3459       dpi->modifiers = NULL;
3460       d_print_comp (dpi, d_left (mods->mod));
3461       dpi->modifiers = hold_modifiers;
3462
3463       if ((dpi->options & DMGL_JAVA) == 0)
3464         d_append_string_constant (dpi, "::");
3465       else
3466         d_append_char (dpi, '.');
3467
3468       dc = d_right (mods->mod);
3469       while (dc->type == D_COMP_RESTRICT_THIS
3470              || dc->type == D_COMP_VOLATILE_THIS
3471              || dc->type == D_COMP_CONST_THIS)
3472         dc = d_left (dc);
3473
3474       d_print_comp (dpi, dc);
3475
3476       dpi->templates = hold_dpt;
3477       return;
3478     }
3479
3480   d_print_mod (dpi, mods->mod);
3481
3482   dpi->templates = hold_dpt;
3483
3484   d_print_mod_list (dpi, mods->next, suffix);
3485 }
3486
3487 /* Print a modifier.  */
3488
3489 static void
3490 d_print_mod (dpi, mod)
3491      struct d_print_info *dpi;
3492      const struct d_comp *mod;
3493 {
3494   switch (mod->type)
3495     {
3496     case D_COMP_RESTRICT:
3497     case D_COMP_RESTRICT_THIS:
3498       d_append_string_constant (dpi, " restrict");
3499       return;
3500     case D_COMP_VOLATILE:
3501     case D_COMP_VOLATILE_THIS:
3502       d_append_string_constant (dpi, " volatile");
3503       return;
3504     case D_COMP_CONST:
3505     case D_COMP_CONST_THIS:
3506       d_append_string_constant (dpi, " const");
3507       return;
3508     case D_COMP_VENDOR_TYPE_QUAL:
3509       d_append_char (dpi, ' ');
3510       d_print_comp (dpi, d_right (mod));
3511       return;
3512     case D_COMP_POINTER:
3513       /* There is no pointer symbol in Java.  */
3514       if ((dpi->options & DMGL_JAVA) == 0)
3515         d_append_char (dpi, '*');
3516       return;
3517     case D_COMP_REFERENCE:
3518       d_append_char (dpi, '&');
3519       return;
3520     case D_COMP_COMPLEX:
3521       d_append_string_constant (dpi, "complex ");
3522       return;
3523     case D_COMP_IMAGINARY:
3524       d_append_string_constant (dpi, "imaginary ");
3525       return;
3526     case D_COMP_PTRMEM_TYPE:
3527       if (d_last_char (dpi) != '(')
3528         d_append_char (dpi, ' ');
3529       d_print_comp (dpi, d_left (mod));
3530       d_append_string_constant (dpi, "::*");
3531       return;
3532     case D_COMP_TYPED_NAME:
3533       d_print_comp (dpi, d_left (mod));
3534       return;
3535     default:
3536       /* Otherwise, we have something that won't go back on the
3537          modifier stack, so we can just print it.  */
3538       d_print_comp (dpi, mod);
3539       return;
3540     }
3541 }
3542
3543 /* Print a function type, except for the return type.  */
3544
3545 static void
3546 d_print_function_type (dpi, dc, mods)
3547      struct d_print_info *dpi;
3548      const struct d_comp *dc;
3549      struct d_print_mod *mods;
3550 {
3551   int need_paren;
3552   int saw_mod;
3553   struct d_print_mod *p;
3554   struct d_print_mod *hold_modifiers;
3555
3556   need_paren = 0;
3557   saw_mod = 0;
3558   for (p = mods; p != NULL; p = p->next)
3559     {
3560       if (p->printed)
3561         break;
3562
3563       saw_mod = 1;
3564       switch (p->mod->type)
3565         {
3566         case D_COMP_RESTRICT:
3567         case D_COMP_VOLATILE:
3568         case D_COMP_CONST:
3569         case D_COMP_VENDOR_TYPE_QUAL:
3570         case D_COMP_POINTER:
3571         case D_COMP_REFERENCE:
3572         case D_COMP_COMPLEX:
3573         case D_COMP_IMAGINARY:
3574         case D_COMP_PTRMEM_TYPE:
3575           need_paren = 1;
3576           break;
3577         case D_COMP_RESTRICT_THIS:
3578         case D_COMP_VOLATILE_THIS:
3579         case D_COMP_CONST_THIS:
3580           break;
3581         default:
3582           break;
3583         }
3584       if (need_paren)
3585         break;
3586     }
3587
3588   if (d_left (dc) != NULL && ! saw_mod)
3589     need_paren = 1;
3590
3591   if (need_paren)
3592     {
3593       switch (d_last_char (dpi))
3594         {
3595         case ' ':
3596         case '(':
3597         case '*':
3598           break;
3599
3600         default:
3601           d_append_char (dpi, ' ');
3602           break;
3603         }
3604
3605       d_append_char (dpi, '(');
3606     }
3607
3608   hold_modifiers = dpi->modifiers;
3609   dpi->modifiers = NULL;
3610
3611   d_print_mod_list (dpi, mods, 0);
3612
3613   if (need_paren)
3614     d_append_char (dpi, ')');
3615
3616   d_append_char (dpi, '(');
3617
3618   if (d_right (dc) != NULL)
3619     d_print_comp (dpi, d_right (dc));
3620
3621   d_append_char (dpi, ')');
3622
3623   d_print_mod_list (dpi, mods, 1);
3624
3625   dpi->modifiers = hold_modifiers;
3626 }
3627
3628 /* Print an array type, except for the element type.  */
3629
3630 static void
3631 d_print_array_type (dpi, dc, mods)
3632      struct d_print_info *dpi;
3633      const struct d_comp *dc;
3634      struct d_print_mod *mods;
3635 {
3636   int need_space;
3637
3638   need_space = 1;
3639   if (mods != NULL)
3640     {
3641       int need_paren;
3642       struct d_print_mod *p;
3643
3644       need_paren = 0;
3645       for (p = mods; p != NULL; p = p->next)
3646         {
3647           if (p->printed)
3648             break;
3649
3650           if (p->mod->type == D_COMP_ARRAY_TYPE)
3651             {
3652               need_space = 0;
3653               break;
3654             }
3655           else
3656             {
3657               need_paren = 1;
3658               need_space = 1;
3659               break;
3660             }
3661         }
3662
3663       if (need_paren)
3664         d_append_string_constant (dpi, " (");
3665
3666       d_print_mod_list (dpi, mods, 0);
3667
3668       if (need_paren)
3669         d_append_char (dpi, ')');
3670     }
3671
3672   if (need_space)
3673     d_append_char (dpi, ' ');
3674
3675   d_append_char (dpi, '[');
3676
3677   if (d_left (dc) != NULL)
3678     d_print_comp (dpi, d_left (dc));
3679
3680   d_append_char (dpi, ']');
3681 }
3682
3683 /* Print an operator in an expression.  */
3684
3685 static void
3686 d_print_expr_op (dpi, dc)
3687      struct d_print_info *dpi;
3688      const struct d_comp *dc;
3689 {
3690   if (dc->type == D_COMP_OPERATOR)
3691     d_append_buffer (dpi, dc->u.s_operator.op->name,
3692                      dc->u.s_operator.op->len);
3693   else
3694     d_print_comp (dpi, dc);
3695 }
3696
3697 /* Print a cast.  */
3698
3699 static void
3700 d_print_cast (dpi, dc)
3701      struct d_print_info *dpi;
3702      const struct d_comp *dc;
3703 {
3704   if (d_left (dc)->type != D_COMP_TEMPLATE)
3705     d_print_comp (dpi, d_left (dc));
3706   else
3707     {
3708       struct d_print_mod *hold_dpm;
3709       struct d_print_template dpt;
3710
3711       /* It appears that for a templated cast operator, we need to put
3712          the template parameters in scope for the operator name, but
3713          not for the parameters.  The effect is that we need to handle
3714          the template printing here.  */
3715
3716       hold_dpm = dpi->modifiers;
3717       dpi->modifiers = NULL;
3718
3719       dpt.next = dpi->templates;
3720       dpi->templates = &dpt;
3721       dpt.template = d_left (dc);
3722
3723       d_print_comp (dpi, d_left (d_left (dc)));
3724
3725       dpi->templates = dpt.next;
3726
3727       if (d_last_char (dpi) == '<')
3728         d_append_char (dpi, ' ');
3729       d_append_char (dpi, '<');
3730       d_print_comp (dpi, d_right (d_left (dc)));
3731       /* Avoid generating two consecutive '>' characters, to avoid
3732          the C++ syntactic ambiguity.  */
3733       if (d_last_char (dpi) == '>')
3734         d_append_char (dpi, ' ');
3735       d_append_char (dpi, '>');
3736
3737       dpi->modifiers = hold_dpm;
3738     }
3739 }
3740
3741 /* Initialize the information structure we use to pass around
3742    information.  */
3743
3744 static void
3745 d_init_info (mangled, options, len, di)
3746      const char *mangled;
3747      int options;
3748      size_t len;
3749      struct d_info *di;
3750 {
3751   di->s = mangled;
3752   di->send = mangled + len;
3753   di->options = options;
3754
3755   di->n = mangled;
3756
3757   /* We can not need more components than twice the number of chars in
3758      the mangled string.  Most components correspond directly to
3759      chars, but the ARGLIST types are exceptions.  */
3760   di->num_comps = 2 * len;
3761   di->next_comp = 0;
3762
3763   /* Similarly, we can not need more substitutions than there are
3764      chars in the mangled string.  */
3765   di->num_subs = len;
3766   di->next_sub = 0;
3767   di->did_subs = 0;
3768
3769   di->last_name = NULL;
3770
3771   di->expansion = 0;
3772 }
3773
3774 /* Entry point for the demangler.  If MANGLED is a g++ v3 ABI mangled
3775    name, return a buffer allocated with malloc holding the demangled
3776    name.  OPTIONS is the usual libiberty demangler options.  On
3777    success, this sets *PALC to the allocated size of the returned
3778    buffer.  On failure, this sets *PALC to 0 for a bad name, or 1 for
3779    a memory allocation failure.  On failure, this returns NULL.  */
3780
3781 static char *
3782 d_demangle (mangled, options, palc)
3783      const char* mangled;
3784      int options;
3785      size_t *palc;
3786 {
3787   size_t len;
3788   int type;
3789   struct d_info di;
3790   struct d_comp *dc;
3791   int estimate;
3792   char *ret;
3793
3794   *palc = 0;
3795
3796   len = strlen (mangled);
3797
3798   if (mangled[0] == '_' && mangled[1] == 'Z')
3799     type = 0;
3800   else if (strncmp (mangled, "_GLOBAL_", 8) == 0
3801            && (mangled[8] == '.' || mangled[8] == '_' || mangled[8] == '$')
3802            && (mangled[9] == 'D' || mangled[9] == 'I')
3803            && mangled[10] == '_')
3804     {
3805       char *r;
3806
3807       r = malloc (40 + len - 11);
3808       if (r == NULL)
3809         *palc = 1;
3810       else
3811         {
3812           if (mangled[9] == 'I')
3813             strcpy (r, "global constructors keyed to ");
3814           else
3815             strcpy (r, "global destructors keyed to ");
3816           strcat (r, mangled + 11);
3817         }
3818       return r;
3819     }
3820   else
3821     {
3822       if ((options & DMGL_TYPES) == 0)
3823         return NULL;
3824       type = 1;
3825     }
3826
3827   d_init_info (mangled, options, len, &di);
3828
3829   {
3830 #ifdef CP_DYNAMIC_ARRAYS
3831     __extension__ struct d_comp comps[di.num_comps];
3832     __extension__ struct d_comp *subs[di.num_subs];
3833
3834     di.comps = &comps[0];
3835     di.subs = &subs[0];
3836 #else
3837     di.comps = (struct d_comp *) malloc (di.num_comps
3838                                          * sizeof (struct d_comp));
3839     di.subs = (struct d_comp **) malloc (di.num_subs
3840                                          * sizeof (struct d_comp *));
3841     if (di.comps == NULL || di.subs == NULL)
3842       {
3843         if (di.comps != NULL)
3844           free (di.comps);
3845         if (di.subs != NULL)
3846           free (di.subs);
3847         *palc = 1;
3848         return NULL;
3849       }
3850 #endif
3851
3852     if (! type)
3853       dc = d_mangled_name (&di, 1);
3854     else
3855       dc = d_type (&di);
3856
3857     /* If DMGL_PARAMS is set, then if we didn't consume the entire
3858        mangled string, then we didn't successfully demangle it.  If
3859        DMGL_PARAMS is not set, we didn't look at the trailing
3860        parameters.  */
3861     if (((options & DMGL_PARAMS) != 0) && d_peek_char (&di) != '\0')
3862       dc = NULL;
3863
3864 #ifdef CP_DEMANGLE_DEBUG
3865     if (dc == NULL)
3866       printf ("failed demangling\n");
3867     else
3868       d_dump (dc, 0);
3869 #endif
3870
3871     /* We try to guess the length of the demangled string, to minimize
3872        calls to realloc during demangling.  */
3873     estimate = len + di.expansion + 10 * di.did_subs;
3874     estimate += estimate / 8;
3875
3876     ret = NULL;
3877     if (dc != NULL)
3878       ret = d_print (options, dc, estimate, palc);
3879
3880 #ifndef CP_DYNAMIC_ARRAYS
3881     free (di.comps);
3882     free (di.subs);
3883 #endif
3884
3885 #ifdef CP_DEMANGLE_DEBUG
3886     if (ret != NULL)
3887       {
3888         int rlen;
3889
3890         rlen = strlen (ret);
3891         if (rlen > 2 * estimate)
3892           printf ("*** Length %d much greater than estimate %d\n",
3893                   rlen, estimate);
3894         else if (rlen > estimate)
3895           printf ("*** Length %d greater than estimate %d\n",
3896                   rlen, estimate);
3897         else if (rlen < estimate / 2)
3898           printf ("*** Length %d much less than estimate %d\n",
3899                   rlen, estimate);
3900       }
3901 #endif
3902   }
3903
3904   return ret;
3905 }
3906
3907 #if defined(IN_LIBGCC2) || defined(IN_GLIBCPP_V3)
3908
3909 extern char *__cxa_demangle PARAMS ((const char *, char *, size_t *, int *));
3910
3911 /* ia64 ABI-mandated entry point in the C++ runtime library for
3912    performing demangling.  MANGLED_NAME is a NUL-terminated character
3913    string containing the name to be demangled.
3914
3915    OUTPUT_BUFFER is a region of memory, allocated with malloc, of
3916    *LENGTH bytes, into which the demangled name is stored.  If
3917    OUTPUT_BUFFER is not long enough, it is expanded using realloc.
3918    OUTPUT_BUFFER may instead be NULL; in that case, the demangled name
3919    is placed in a region of memory allocated with malloc.
3920
3921    If LENGTH is non-NULL, the length of the buffer conaining the
3922    demangled name, is placed in *LENGTH.
3923
3924    The return value is a pointer to the start of the NUL-terminated
3925    demangled name, or NULL if the demangling fails.  The caller is
3926    responsible for deallocating this memory using free.
3927
3928    *STATUS is set to one of the following values:
3929       0: The demangling operation succeeded.
3930      -1: A memory allocation failure occurred.
3931      -2: MANGLED_NAME is not a valid name under the C++ ABI mangling rules.
3932      -3: One of the arguments is invalid.
3933
3934    The demangling is performed using the C++ ABI mangling rules, with
3935    GNU extensions.  */
3936
3937 char *
3938 __cxa_demangle (mangled_name, output_buffer, length, status)
3939      const char *mangled_name;
3940      char *output_buffer;
3941      size_t *length;
3942      int *status;
3943 {
3944   char *demangled;
3945   size_t alc;
3946
3947   if (status == NULL)
3948     return NULL;
3949
3950   if (mangled_name == NULL)
3951     {
3952       *status = -3;
3953       return NULL;
3954     }
3955
3956   if (output_buffer != NULL && length == NULL)
3957     {
3958       *status = -3;
3959       return NULL;
3960     }
3961
3962   demangled = d_demangle (mangled_name, DMGL_TYPES, &alc);
3963
3964   if (demangled == NULL)
3965     {
3966       if (alc == 1)
3967         *status = -1;
3968       else
3969         *status = -2;
3970       return NULL;
3971     }
3972
3973   if (output_buffer == NULL)
3974     {
3975       if (length != NULL)
3976         *length = alc;
3977     }
3978   else
3979     {
3980       if (strlen (demangled) < *length)
3981         {
3982           strcpy (output_buffer, demangled);
3983           free (demangled);
3984           demangled = output_buffer;
3985         }
3986       else
3987         {
3988           free (output_buffer);
3989           *length = alc;
3990         }
3991     }
3992
3993   *status = 0;
3994
3995   return demangled;
3996 }
3997
3998 #else /* ! (IN_LIBGCC2 || IN_GLIBCPP_V3) */
3999
4000 /* Entry point for libiberty demangler.  If MANGLED is a g++ v3 ABI
4001    mangled name, return a buffer allocated with malloc holding the
4002    demangled name.  Otherwise, return NULL.  */
4003
4004 char *
4005 cplus_demangle_v3 (mangled, options)
4006      const char* mangled;
4007      int options;
4008 {
4009   size_t alc;
4010
4011   return d_demangle (mangled, options, &alc);
4012 }
4013
4014 /* Demangle a Java symbol.  Java uses a subset of the V3 ABI C++ mangling 
4015    conventions, but the output formatting is a little different.
4016    This instructs the C++ demangler not to emit pointer characters ("*"), and 
4017    to use Java's namespace separator symbol ("." instead of "::").  It then 
4018    does an additional pass over the demangled output to replace instances 
4019    of JArray<TYPE> with TYPE[].  */
4020
4021 char *
4022 java_demangle_v3 (mangled)
4023      const char* mangled;
4024 {
4025   size_t alc;
4026   char *demangled;
4027   int nesting;
4028   char *from;
4029   char *to;
4030
4031   demangled = d_demangle (mangled, DMGL_JAVA | DMGL_PARAMS, &alc);
4032
4033   if (demangled == NULL)
4034     return NULL;
4035
4036   nesting = 0;
4037   from = demangled;
4038   to = from;
4039   while (*from != '\0')
4040     {
4041       if (strncmp (from, "JArray<", 7) == 0)
4042         {
4043           from += 7;
4044           ++nesting;
4045         }
4046       else if (nesting > 0 && *from == '>')
4047         {
4048           while (to > demangled && to[-1] == ' ')
4049             --to;
4050           *to++ = '[';
4051           *to++ = ']';
4052           --nesting;
4053           ++from;
4054         }
4055       else
4056         *to++ = *from++;
4057     }
4058
4059   *to = '\0';
4060
4061   return demangled;
4062 }
4063
4064 #endif /* IN_LIBGCC2 || IN_GLIBCPP_V3 */
4065
4066 #ifndef IN_GLIBCPP_V3
4067
4068 /* Demangle a string in order to find out whether it is a constructor
4069    or destructor.  Return non-zero on success.  Set *CTOR_KIND and
4070    *DTOR_KIND appropriately.  */
4071
4072 static int
4073 is_ctor_or_dtor (mangled, ctor_kind, dtor_kind)
4074      const char *mangled;
4075      enum gnu_v3_ctor_kinds *ctor_kind;
4076      enum gnu_v3_dtor_kinds *dtor_kind;
4077 {
4078   struct d_info di;
4079   struct d_comp *dc;
4080   int ret;
4081
4082   *ctor_kind = (enum gnu_v3_ctor_kinds) 0;
4083   *dtor_kind = (enum gnu_v3_dtor_kinds) 0;
4084
4085   d_init_info (mangled, DMGL_GNU_V3, strlen (mangled), &di);
4086
4087   {
4088 #ifdef CP_DYNAMIC_ARRAYS
4089     __extension__ struct d_comp comps[di.num_comps];
4090     __extension__ struct d_comp *subs[di.num_subs];
4091
4092     di.comps = &comps[0];
4093     di.subs = &subs[0];
4094 #else
4095     di.comps = (struct d_comp *) malloc (di.num_comps
4096                                          * sizeof (struct d_comp));
4097     di.subs = (struct d_comp **) malloc (di.num_subs
4098                                          * sizeof (struct d_comp *));
4099     if (di.comps == NULL || di.subs == NULL)
4100       {
4101         if (di.comps != NULL)
4102           free (di.comps);
4103         if (di.subs != NULL)
4104           free (di.subs);
4105         return 0;
4106       }
4107 #endif
4108
4109     dc = d_mangled_name (&di, 1);
4110
4111     /* Note that because we did not pass DMGL_PARAMS, we don't expect
4112        to demangle the entire string.  */
4113
4114     ret = 0;
4115     while (dc != NULL)
4116       {
4117         switch (dc->type)
4118           {
4119           default:
4120             dc = NULL;
4121             break;
4122           case D_COMP_TYPED_NAME:
4123           case D_COMP_TEMPLATE:
4124           case D_COMP_RESTRICT_THIS:
4125           case D_COMP_VOLATILE_THIS:
4126           case D_COMP_CONST_THIS:
4127             dc = d_left (dc);
4128             break;
4129           case D_COMP_QUAL_NAME:
4130           case D_COMP_LOCAL_NAME:
4131             dc = d_right (dc);
4132             break;
4133           case D_COMP_CTOR:
4134             *ctor_kind = dc->u.s_ctor.kind;
4135             ret = 1;
4136             dc = NULL;
4137             break;
4138           case D_COMP_DTOR:
4139             *dtor_kind = dc->u.s_dtor.kind;
4140             ret = 1;
4141             dc = NULL;
4142             break;
4143           }
4144       }
4145
4146 #ifndef CP_DYNAMIC_ARRAYS
4147     free (di.subs);
4148     free (di.comps);
4149 #endif
4150   }
4151
4152   return ret;
4153 }
4154
4155 /* Return whether NAME is the mangled form of a g++ V3 ABI constructor
4156    name.  A non-zero return indicates the type of constructor.  */
4157
4158 enum gnu_v3_ctor_kinds
4159 is_gnu_v3_mangled_ctor (name)
4160      const char *name;
4161 {
4162   enum gnu_v3_ctor_kinds ctor_kind;
4163   enum gnu_v3_dtor_kinds dtor_kind;
4164
4165   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
4166     return (enum gnu_v3_ctor_kinds) 0;
4167   return ctor_kind;
4168 }
4169
4170
4171 /* Return whether NAME is the mangled form of a g++ V3 ABI destructor
4172    name.  A non-zero return indicates the type of destructor.  */
4173
4174 enum gnu_v3_dtor_kinds
4175 is_gnu_v3_mangled_dtor (name)
4176      const char *name;
4177 {
4178   enum gnu_v3_ctor_kinds ctor_kind;
4179   enum gnu_v3_dtor_kinds dtor_kind;
4180
4181   if (! is_ctor_or_dtor (name, &ctor_kind, &dtor_kind))
4182     return (enum gnu_v3_dtor_kinds) 0;
4183   return dtor_kind;
4184 }
4185
4186 #endif /* IN_GLIBCPP_V3 */
4187
4188 #ifdef STANDALONE_DEMANGLER
4189
4190 #include "getopt.h"
4191 #include "dyn-string.h"
4192
4193 static void print_usage PARAMS ((FILE* fp, int exit_value));
4194
4195 #define IS_ALPHA(CHAR)                                                  \
4196   (((CHAR) >= 'a' && (CHAR) <= 'z')                                     \
4197    || ((CHAR) >= 'A' && (CHAR) <= 'Z'))
4198
4199 /* Non-zero if CHAR is a character than can occur in a mangled name.  */
4200 #define is_mangled_char(CHAR)                                           \
4201   (IS_ALPHA (CHAR) || IS_DIGIT (CHAR)                                   \
4202    || (CHAR) == '_' || (CHAR) == '.' || (CHAR) == '$')
4203
4204 /* The name of this program, as invoked.  */
4205 const char* program_name;
4206
4207 /* Prints usage summary to FP and then exits with EXIT_VALUE.  */
4208
4209 static void
4210 print_usage (fp, exit_value)
4211      FILE* fp;
4212      int exit_value;
4213 {
4214   fprintf (fp, "Usage: %s [options] [names ...]\n", program_name);
4215   fprintf (fp, "Options:\n");
4216   fprintf (fp, "  -h,--help       Display this message.\n");
4217   fprintf (fp, "  -p,--no-params  Don't display function parameters\n");
4218   fprintf (fp, "  -v,--verbose    Produce verbose demanglings.\n");
4219   fprintf (fp, "If names are provided, they are demangled.  Otherwise filters standard input.\n");
4220
4221   exit (exit_value);
4222 }
4223
4224 /* Option specification for getopt_long.  */
4225 static const struct option long_options[] = 
4226 {
4227   { "help",      no_argument, NULL, 'h' },
4228   { "no-params", no_argument, NULL, 'p' },
4229   { "verbose",   no_argument, NULL, 'v' },
4230   { NULL,        no_argument, NULL, 0   },
4231 };
4232
4233 /* Main entry for a demangling filter executable.  It will demangle
4234    its command line arguments, if any.  If none are provided, it will
4235    filter stdin to stdout, replacing any recognized mangled C++ names
4236    with their demangled equivalents.  */
4237
4238 int
4239 main (argc, argv)
4240      int argc;
4241      char *argv[];
4242 {
4243   int i;
4244   int opt_char;
4245   int options = DMGL_PARAMS | DMGL_ANSI | DMGL_TYPES;
4246
4247   /* Use the program name of this program, as invoked.  */
4248   program_name = argv[0];
4249
4250   /* Parse options.  */
4251   do 
4252     {
4253       opt_char = getopt_long (argc, argv, "hpv", long_options, NULL);
4254       switch (opt_char)
4255         {
4256         case '?':  /* Unrecognized option.  */
4257           print_usage (stderr, 1);
4258           break;
4259
4260         case 'h':
4261           print_usage (stdout, 0);
4262           break;
4263
4264         case 'p':
4265           options &= ~ DMGL_PARAMS;
4266           break;
4267
4268         case 'v':
4269           options |= DMGL_VERBOSE;
4270           break;
4271         }
4272     }
4273   while (opt_char != -1);
4274
4275   if (optind == argc) 
4276     /* No command line arguments were provided.  Filter stdin.  */
4277     {
4278       dyn_string_t mangled = dyn_string_new (3);
4279       char *s;
4280
4281       /* Read all of input.  */
4282       while (!feof (stdin))
4283         {
4284           char c;
4285
4286           /* Pile characters into mangled until we hit one that can't
4287              occur in a mangled name.  */
4288           c = getchar ();
4289           while (!feof (stdin) && is_mangled_char (c))
4290             {
4291               dyn_string_append_char (mangled, c);
4292               if (feof (stdin))
4293                 break;
4294               c = getchar ();
4295             }
4296
4297           if (dyn_string_length (mangled) > 0)
4298             {
4299               s = cplus_demangle_v3 (dyn_string_buf (mangled), options);
4300
4301               if (s != NULL)
4302                 {
4303                   fputs (s, stdout);
4304                   free (s);
4305                 }
4306               else
4307                 {
4308                   /* It might not have been a mangled name.  Print the
4309                      original text.  */
4310                   fputs (dyn_string_buf (mangled), stdout);
4311                 }
4312
4313               dyn_string_clear (mangled);
4314             }
4315
4316           /* If we haven't hit EOF yet, we've read one character that
4317              can't occur in a mangled name, so print it out.  */
4318           if (!feof (stdin))
4319             putchar (c);
4320         }
4321
4322       dyn_string_delete (mangled);
4323     }
4324   else
4325     /* Demangle command line arguments.  */
4326     {
4327       /* Loop over command line arguments.  */
4328       for (i = optind; i < argc; ++i)
4329         {
4330           char *s;
4331
4332           /* Attempt to demangle.  */
4333           s = cplus_demangle_v3 (argv[i], options);
4334
4335           /* If it worked, print the demangled name.  */
4336           if (s != NULL)
4337             {
4338               printf ("%s\n", s);
4339               free (s);
4340             }
4341           else
4342             fprintf (stderr, "Failed: %s\n", argv[i]);
4343         }
4344     }
4345
4346   return 0;
4347 }
4348
4349 #endif /* STANDALONE_DEMANGLER */