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