b66257513d69bba46de30b82455bbbb3d416c918
[external/binutils.git] / gdb / cp-name-parser.y
1 /* YACC parser for C++ names, for GDB.
2
3    Copyright (C) 2003-2018 Free Software Foundation, Inc.
4
5    Parts of the lexer are based on c-exp.y from GDB.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 /* Note that malloc's and realloc's in this file are transformed to
23    xmalloc and xrealloc respectively by the same sed command in the
24    makefile that remaps any other malloc/realloc inserted by the parser
25    generator.  Doing this with #defines and trying to control the interaction
26    with include files (<malloc.h> and <stdlib.h> for example) just became
27    too messy, particularly when such includes can be inserted at random
28    times by the parser generator.  */
29
30 /* The Bison manual says that %pure-parser is deprecated, but we use
31    it anyway because it also works with Byacc.  That is also why
32    this uses %lex-param and %parse-param rather than the simpler
33    %param -- Byacc does not support the latter.  */
34 %pure-parser
35 %lex-param {struct cpname_state *state}
36 %parse-param {struct cpname_state *state}
37
38 %{
39
40 #include "defs.h"
41
42 #include <unistd.h>
43 #include "safe-ctype.h"
44 #include "demangle.h"
45 #include "cp-support.h"
46 #include "c-support.h"
47
48 /* Function used to avoid direct calls to fprintf
49    in the code generated by the bison parser.  */
50
51 extern void parser_fprintf (FILE *, const char *, ...) ATTRIBUTE_PRINTF (2, 3);
52
53 #define GDB_YY_REMAP_PREFIX cpname
54 #include "yy-remap.h"
55
56 /* The components built by the parser are allocated ahead of time,
57    and cached in this structure.  */
58
59 #define ALLOC_CHUNK 100
60
61 struct demangle_info {
62   int used;
63   struct demangle_info *next;
64   struct demangle_component comps[ALLOC_CHUNK];
65 };
66
67 struct cpname_state
68 {
69 /* LEXPTR is the current pointer into our lex buffer.  PREV_LEXPTR
70    is the start of the last token lexed, only used for diagnostics.
71    ERROR_LEXPTR is the first place an error occurred.  GLOBAL_ERRMSG
72    is the first error message encountered.  */
73
74   const char *lexptr, *prev_lexptr, *error_lexptr, *global_errmsg;
75
76   struct demangle_info *demangle_info;
77
78   /* The parse tree created by the parser is stored here after a
79      successful parse.  */
80
81   struct demangle_component *global_result;
82 };
83
84 static struct demangle_component *
85 d_grab (cpname_state *state)
86 {
87   struct demangle_info *more;
88
89   if (state->demangle_info->used >= ALLOC_CHUNK)
90     {
91       if (state->demangle_info->next == NULL)
92         {
93           more = XNEW (struct demangle_info);
94           more->next = NULL;
95           state->demangle_info->next = more;
96         }
97       else
98         more = state->demangle_info->next;
99
100       more->used = 0;
101       state->demangle_info = more;
102     }
103   return &state->demangle_info->comps[state->demangle_info->used++];
104 }
105
106 /* Prototypes for helper functions used when constructing the parse
107    tree.  */
108
109 static struct demangle_component *d_qualify (cpname_state *state,
110                                              struct demangle_component *, int,
111                                              int);
112
113 static struct demangle_component *d_int_type (cpname_state *state, int);
114
115 static struct demangle_component *d_unary (cpname_state *state, const char *,
116                                            struct demangle_component *);
117 static struct demangle_component *d_binary (cpname_state *state, const char *,
118                                             struct demangle_component *,
119                                             struct demangle_component *);
120
121 /* Flags passed to d_qualify.  */
122
123 #define QUAL_CONST 1
124 #define QUAL_RESTRICT 2
125 #define QUAL_VOLATILE 4
126
127 /* Flags passed to d_int_type.  */
128
129 #define INT_CHAR        (1 << 0)
130 #define INT_SHORT       (1 << 1)
131 #define INT_LONG        (1 << 2)
132 #define INT_LLONG       (1 << 3)
133
134 #define INT_SIGNED      (1 << 4)
135 #define INT_UNSIGNED    (1 << 5)
136
137 /* Enable yydebug for the stand-alone parser.  */
138 #ifdef TEST_CPNAMES
139 # define YYDEBUG        1
140 #endif
141
142 /* Helper functions.  These wrap the demangler tree interface, handle
143    allocation from our global store, and return the allocated component.  */
144
145 static struct demangle_component *
146 fill_comp (cpname_state *state,
147            enum demangle_component_type d_type, struct demangle_component *lhs,
148            struct demangle_component *rhs)
149 {
150   struct demangle_component *ret = d_grab (state);
151   int i;
152
153   i = cplus_demangle_fill_component (ret, d_type, lhs, rhs);
154   gdb_assert (i);
155
156   return ret;
157 }
158
159 static struct demangle_component *
160 make_operator (cpname_state *state, const char *name, int args)
161 {
162   struct demangle_component *ret = d_grab (state);
163   int i;
164
165   i = cplus_demangle_fill_operator (ret, name, args);
166   gdb_assert (i);
167
168   return ret;
169 }
170
171 static struct demangle_component *
172 make_dtor (cpname_state *state, enum gnu_v3_dtor_kinds kind,
173            struct demangle_component *name)
174 {
175   struct demangle_component *ret = d_grab (state);
176   int i;
177
178   i = cplus_demangle_fill_dtor (ret, kind, name);
179   gdb_assert (i);
180
181   return ret;
182 }
183
184 static struct demangle_component *
185 make_builtin_type (cpname_state *state, const char *name)
186 {
187   struct demangle_component *ret = d_grab (state);
188   int i;
189
190   i = cplus_demangle_fill_builtin_type (ret, name);
191   gdb_assert (i);
192
193   return ret;
194 }
195
196 static struct demangle_component *
197 make_name (cpname_state *state, const char *name, int len)
198 {
199   struct demangle_component *ret = d_grab (state);
200   int i;
201
202   i = cplus_demangle_fill_name (ret, name, len);
203   gdb_assert (i);
204
205   return ret;
206 }
207
208 #define d_left(dc) (dc)->u.s_binary.left
209 #define d_right(dc) (dc)->u.s_binary.right
210
211 %}
212
213 %union
214   {
215     struct demangle_component *comp;
216     struct nested {
217       struct demangle_component *comp;
218       struct demangle_component **last;
219     } nested;
220     struct {
221       struct demangle_component *comp, *last;
222     } nested1;
223     struct {
224       struct demangle_component *comp, **last;
225       struct nested fn;
226       struct demangle_component *start;
227       int fold_flag;
228     } abstract;
229     int lval;
230     const char *opname;
231   }
232
233 %{
234 static int yylex (YYSTYPE *, cpname_state *);
235 static void yyerror (cpname_state *, const char *);
236 %}
237
238 %type <comp> exp exp1 type start start_opt oper colon_name
239 %type <comp> unqualified_name colon_ext_name
240 %type <comp> templ template_arg
241 %type <comp> builtin_type
242 %type <comp> typespec_2 array_indicator
243 %type <comp> colon_ext_only ext_only_name
244
245 %type <comp> demangler_special function conversion_op
246 %type <nested> conversion_op_name
247
248 %type <abstract> abstract_declarator direct_abstract_declarator
249 %type <abstract> abstract_declarator_fn
250 %type <nested> declarator direct_declarator function_arglist
251
252 %type <nested> declarator_1 direct_declarator_1
253
254 %type <nested> template_params function_args
255 %type <nested> ptr_operator
256
257 %type <nested1> nested_name
258
259 %type <lval> qualifier qualifiers qualifiers_opt
260
261 %type <lval> int_part int_seq
262
263 %token <comp> INT
264 %token <comp> FLOAT
265
266 %token <comp> NAME
267 %type <comp> name
268
269 %token STRUCT CLASS UNION ENUM SIZEOF UNSIGNED COLONCOLON
270 %token TEMPLATE
271 %token ERROR
272 %token NEW DELETE OPERATOR
273 %token STATIC_CAST REINTERPRET_CAST DYNAMIC_CAST
274
275 /* Special type cases, put in to allow the parser to distinguish different
276    legal basetypes.  */
277 %token SIGNED_KEYWORD LONG SHORT INT_KEYWORD CONST_KEYWORD VOLATILE_KEYWORD DOUBLE_KEYWORD BOOL
278 %token ELLIPSIS RESTRICT VOID FLOAT_KEYWORD CHAR WCHAR_T
279
280 %token <opname> ASSIGN_MODIFY
281
282 /* C++ */
283 %token TRUEKEYWORD
284 %token FALSEKEYWORD
285
286 /* Non-C++ things we get from the demangler.  */
287 %token <lval> DEMANGLER_SPECIAL
288 %token CONSTRUCTION_VTABLE CONSTRUCTION_IN
289
290 /* Precedence declarations.  */
291
292 /* Give NAME lower precedence than COLONCOLON, so that nested_name will
293    associate greedily.  */
294 %nonassoc NAME
295
296 /* Give NEW and DELETE lower precedence than ']', because we can not
297    have an array of type operator new.  This causes NEW '[' to be
298    parsed as operator new[].  */
299 %nonassoc NEW DELETE
300
301 /* Give VOID higher precedence than NAME.  Then we can use %prec NAME
302    to prefer (VOID) to (function_args).  */
303 %nonassoc VOID
304
305 /* Give VOID lower precedence than ')' for similar reasons.  */
306 %nonassoc ')'
307
308 %left ','
309 %right '=' ASSIGN_MODIFY
310 %right '?'
311 %left OROR
312 %left ANDAND
313 %left '|'
314 %left '^'
315 %left '&'
316 %left EQUAL NOTEQUAL
317 %left '<' '>' LEQ GEQ
318 %left LSH RSH
319 %left '@'
320 %left '+' '-'
321 %left '*' '/' '%'
322 %right UNARY INCREMENT DECREMENT
323
324 /* We don't need a precedence for '(' in this reduced grammar, and it
325    can mask some unpleasant bugs, so disable it for now.  */
326
327 %right ARROW '.' '[' /* '(' */
328 %left COLONCOLON
329
330 \f
331 %%
332
333 result          :       start
334                         { state->global_result = $1; }
335                 ;
336
337 start           :       type
338
339                 |       demangler_special
340
341                 |       function
342
343                 ;
344
345 start_opt       :       /* */
346                         { $$ = NULL; }
347                 |       COLONCOLON start
348                         { $$ = $2; }
349                 ;
350
351 function
352                 /* Function with a return type.  declarator_1 is used to prevent
353                    ambiguity with the next rule.  */
354                 :       typespec_2 declarator_1
355                         { $$ = $2.comp;
356                           *$2.last = $1;
357                         }
358
359                 /* Function without a return type.  We need to use typespec_2
360                    to prevent conflicts from qualifiers_opt - harmless.  The
361                    start_opt is used to handle "function-local" variables and
362                    types.  */
363                 |       typespec_2 function_arglist start_opt
364                         { $$ = fill_comp (state, DEMANGLE_COMPONENT_TYPED_NAME,
365                                           $1, $2.comp);
366                           if ($3)
367                             $$ = fill_comp (state,
368                                             DEMANGLE_COMPONENT_LOCAL_NAME,
369                                             $$, $3);
370                         }
371                 |       colon_ext_only function_arglist start_opt
372                         { $$ = fill_comp (state, DEMANGLE_COMPONENT_TYPED_NAME, $1, $2.comp);
373                           if ($3) $$ = fill_comp (state, DEMANGLE_COMPONENT_LOCAL_NAME, $$, $3); }
374
375                 |       conversion_op_name start_opt
376                         { $$ = $1.comp;
377                           if ($2) $$ = fill_comp (state, DEMANGLE_COMPONENT_LOCAL_NAME, $$, $2); }
378                 |       conversion_op_name abstract_declarator_fn
379                         { if ($2.last)
380                             {
381                                /* First complete the abstract_declarator's type using
382                                   the typespec from the conversion_op_name.  */
383                               *$2.last = *$1.last;
384                               /* Then complete the conversion_op_name with the type.  */
385                               *$1.last = $2.comp;
386                             }
387                           /* If we have an arglist, build a function type.  */
388                           if ($2.fn.comp)
389                             $$ = fill_comp (state, DEMANGLE_COMPONENT_TYPED_NAME, $1.comp, $2.fn.comp);
390                           else
391                             $$ = $1.comp;
392                           if ($2.start) $$ = fill_comp (state, DEMANGLE_COMPONENT_LOCAL_NAME, $$, $2.start);
393                         }
394                 ;
395
396 demangler_special
397                 :       DEMANGLER_SPECIAL start
398                         { $$ = fill_comp (state, (enum demangle_component_type) $1, $2, NULL); }
399                 |       CONSTRUCTION_VTABLE start CONSTRUCTION_IN start
400                         { $$ = fill_comp (state, DEMANGLE_COMPONENT_CONSTRUCTION_VTABLE, $2, $4); }
401                 ;
402
403 oper    :       OPERATOR NEW
404                         {
405                           /* Match the whitespacing of cplus_demangle_operators.
406                              It would abort on unrecognized string otherwise.  */
407                           $$ = make_operator (state, "new", 3);
408                         }
409                 |       OPERATOR DELETE
410                         {
411                           /* Match the whitespacing of cplus_demangle_operators.
412                              It would abort on unrecognized string otherwise.  */
413                           $$ = make_operator (state, "delete ", 1);
414                         }
415                 |       OPERATOR NEW '[' ']'
416                         {
417                           /* Match the whitespacing of cplus_demangle_operators.
418                              It would abort on unrecognized string otherwise.  */
419                           $$ = make_operator (state, "new[]", 3);
420                         }
421                 |       OPERATOR DELETE '[' ']'
422                         {
423                           /* Match the whitespacing of cplus_demangle_operators.
424                              It would abort on unrecognized string otherwise.  */
425                           $$ = make_operator (state, "delete[] ", 1);
426                         }
427                 |       OPERATOR '+'
428                         { $$ = make_operator (state, "+", 2); }
429                 |       OPERATOR '-'
430                         { $$ = make_operator (state, "-", 2); }
431                 |       OPERATOR '*'
432                         { $$ = make_operator (state, "*", 2); }
433                 |       OPERATOR '/'
434                         { $$ = make_operator (state, "/", 2); }
435                 |       OPERATOR '%'
436                         { $$ = make_operator (state, "%", 2); }
437                 |       OPERATOR '^'
438                         { $$ = make_operator (state, "^", 2); }
439                 |       OPERATOR '&'
440                         { $$ = make_operator (state, "&", 2); }
441                 |       OPERATOR '|'
442                         { $$ = make_operator (state, "|", 2); }
443                 |       OPERATOR '~'
444                         { $$ = make_operator (state, "~", 1); }
445                 |       OPERATOR '!'
446                         { $$ = make_operator (state, "!", 1); }
447                 |       OPERATOR '='
448                         { $$ = make_operator (state, "=", 2); }
449                 |       OPERATOR '<'
450                         { $$ = make_operator (state, "<", 2); }
451                 |       OPERATOR '>'
452                         { $$ = make_operator (state, ">", 2); }
453                 |       OPERATOR ASSIGN_MODIFY
454                         { $$ = make_operator (state, $2, 2); }
455                 |       OPERATOR LSH
456                         { $$ = make_operator (state, "<<", 2); }
457                 |       OPERATOR RSH
458                         { $$ = make_operator (state, ">>", 2); }
459                 |       OPERATOR EQUAL
460                         { $$ = make_operator (state, "==", 2); }
461                 |       OPERATOR NOTEQUAL
462                         { $$ = make_operator (state, "!=", 2); }
463                 |       OPERATOR LEQ
464                         { $$ = make_operator (state, "<=", 2); }
465                 |       OPERATOR GEQ
466                         { $$ = make_operator (state, ">=", 2); }
467                 |       OPERATOR ANDAND
468                         { $$ = make_operator (state, "&&", 2); }
469                 |       OPERATOR OROR
470                         { $$ = make_operator (state, "||", 2); }
471                 |       OPERATOR INCREMENT
472                         { $$ = make_operator (state, "++", 1); }
473                 |       OPERATOR DECREMENT
474                         { $$ = make_operator (state, "--", 1); }
475                 |       OPERATOR ','
476                         { $$ = make_operator (state, ",", 2); }
477                 |       OPERATOR ARROW '*'
478                         { $$ = make_operator (state, "->*", 2); }
479                 |       OPERATOR ARROW
480                         { $$ = make_operator (state, "->", 2); }
481                 |       OPERATOR '(' ')'
482                         { $$ = make_operator (state, "()", 2); }
483                 |       OPERATOR '[' ']'
484                         { $$ = make_operator (state, "[]", 2); }
485                 ;
486
487                 /* Conversion operators.  We don't try to handle some of
488                    the wackier demangler output for function pointers,
489                    since it's not clear that it's parseable.  */
490 conversion_op
491                 :       OPERATOR typespec_2
492                         { $$ = fill_comp (state, DEMANGLE_COMPONENT_CONVERSION, $2, NULL); }
493                 ;
494
495 conversion_op_name
496                 :       nested_name conversion_op
497                         { $$.comp = $1.comp;
498                           d_right ($1.last) = $2;
499                           $$.last = &d_left ($2);
500                         }
501                 |       conversion_op
502                         { $$.comp = $1;
503                           $$.last = &d_left ($1);
504                         }
505                 |       COLONCOLON nested_name conversion_op
506                         { $$.comp = $2.comp;
507                           d_right ($2.last) = $3;
508                           $$.last = &d_left ($3);
509                         }
510                 |       COLONCOLON conversion_op
511                         { $$.comp = $2;
512                           $$.last = &d_left ($2);
513                         }
514                 ;
515
516 /* DEMANGLE_COMPONENT_NAME */
517 /* This accepts certain invalid placements of '~'.  */
518 unqualified_name:       oper
519                 |       oper '<' template_params '>'
520                         { $$ = fill_comp (state, DEMANGLE_COMPONENT_TEMPLATE, $1, $3.comp); }
521                 |       '~' NAME
522                         { $$ = make_dtor (state, gnu_v3_complete_object_dtor, $2); }
523                 ;
524
525 /* This rule is used in name and nested_name, and expanded inline there
526    for efficiency.  */
527 /*
528 scope_id        :       NAME
529                 |       template
530                 ;
531 */
532
533 colon_name      :       name
534                 |       COLONCOLON name
535                         { $$ = $2; }
536                 ;
537
538 /* DEMANGLE_COMPONENT_QUAL_NAME */
539 /* DEMANGLE_COMPONENT_CTOR / DEMANGLE_COMPONENT_DTOR ? */
540 name            :       nested_name NAME %prec NAME
541                         { $$ = $1.comp; d_right ($1.last) = $2; }
542                 |       NAME %prec NAME
543                 |       nested_name templ %prec NAME
544                         { $$ = $1.comp; d_right ($1.last) = $2; }
545                 |       templ %prec NAME
546                 ;
547
548 colon_ext_name  :       colon_name
549                 |       colon_ext_only
550                 ;
551
552 colon_ext_only  :       ext_only_name
553                 |       COLONCOLON ext_only_name
554                         { $$ = $2; }
555                 ;
556
557 ext_only_name   :       nested_name unqualified_name
558                         { $$ = $1.comp; d_right ($1.last) = $2; }
559                 |       unqualified_name
560                 ;
561
562 nested_name     :       NAME COLONCOLON
563                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_QUAL_NAME, $1, NULL);
564                           $$.last = $$.comp;
565                         }
566                 |       nested_name NAME COLONCOLON
567                         { $$.comp = $1.comp;
568                           d_right ($1.last) = fill_comp (state, DEMANGLE_COMPONENT_QUAL_NAME, $2, NULL);
569                           $$.last = d_right ($1.last);
570                         }
571                 |       templ COLONCOLON
572                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_QUAL_NAME, $1, NULL);
573                           $$.last = $$.comp;
574                         }
575                 |       nested_name templ COLONCOLON
576                         { $$.comp = $1.comp;
577                           d_right ($1.last) = fill_comp (state, DEMANGLE_COMPONENT_QUAL_NAME, $2, NULL);
578                           $$.last = d_right ($1.last);
579                         }
580                 ;
581
582 /* DEMANGLE_COMPONENT_TEMPLATE */
583 /* DEMANGLE_COMPONENT_TEMPLATE_ARGLIST */
584 templ   :       NAME '<' template_params '>'
585                         { $$ = fill_comp (state, DEMANGLE_COMPONENT_TEMPLATE, $1, $3.comp); }
586                 ;
587
588 template_params :       template_arg
589                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_TEMPLATE_ARGLIST, $1, NULL);
590                         $$.last = &d_right ($$.comp); }
591                 |       template_params ',' template_arg
592                         { $$.comp = $1.comp;
593                           *$1.last = fill_comp (state, DEMANGLE_COMPONENT_TEMPLATE_ARGLIST, $3, NULL);
594                           $$.last = &d_right (*$1.last);
595                         }
596                 ;
597
598 /* "type" is inlined into template_arg and function_args.  */
599
600 /* Also an integral constant-expression of integral type, and a
601    pointer to member (?) */
602 template_arg    :       typespec_2
603                 |       typespec_2 abstract_declarator
604                         { $$ = $2.comp;
605                           *$2.last = $1;
606                         }
607                 |       '&' start
608                         { $$ = fill_comp (state, DEMANGLE_COMPONENT_UNARY, make_operator (state, "&", 1), $2); }
609                 |       '&' '(' start ')'
610                         { $$ = fill_comp (state, DEMANGLE_COMPONENT_UNARY, make_operator (state, "&", 1), $3); }
611                 |       exp
612                 ;
613
614 function_args   :       typespec_2
615                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_ARGLIST, $1, NULL);
616                           $$.last = &d_right ($$.comp);
617                         }
618                 |       typespec_2 abstract_declarator
619                         { *$2.last = $1;
620                           $$.comp = fill_comp (state, DEMANGLE_COMPONENT_ARGLIST, $2.comp, NULL);
621                           $$.last = &d_right ($$.comp);
622                         }
623                 |       function_args ',' typespec_2
624                         { *$1.last = fill_comp (state, DEMANGLE_COMPONENT_ARGLIST, $3, NULL);
625                           $$.comp = $1.comp;
626                           $$.last = &d_right (*$1.last);
627                         }
628                 |       function_args ',' typespec_2 abstract_declarator
629                         { *$4.last = $3;
630                           *$1.last = fill_comp (state, DEMANGLE_COMPONENT_ARGLIST, $4.comp, NULL);
631                           $$.comp = $1.comp;
632                           $$.last = &d_right (*$1.last);
633                         }
634                 |       function_args ',' ELLIPSIS
635                         { *$1.last
636                             = fill_comp (state, DEMANGLE_COMPONENT_ARGLIST,
637                                            make_builtin_type (state, "..."),
638                                            NULL);
639                           $$.comp = $1.comp;
640                           $$.last = &d_right (*$1.last);
641                         }
642                 ;
643
644 function_arglist:       '(' function_args ')' qualifiers_opt %prec NAME
645                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_FUNCTION_TYPE, NULL, $2.comp);
646                           $$.last = &d_left ($$.comp);
647                           $$.comp = d_qualify (state, $$.comp, $4, 1); }
648                 |       '(' VOID ')' qualifiers_opt
649                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_FUNCTION_TYPE, NULL, NULL);
650                           $$.last = &d_left ($$.comp);
651                           $$.comp = d_qualify (state, $$.comp, $4, 1); }
652                 |       '(' ')' qualifiers_opt
653                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_FUNCTION_TYPE, NULL, NULL);
654                           $$.last = &d_left ($$.comp);
655                           $$.comp = d_qualify (state, $$.comp, $3, 1); }
656                 ;
657
658 /* Should do something about DEMANGLE_COMPONENT_VENDOR_TYPE_QUAL */
659 qualifiers_opt  :       /* epsilon */
660                         { $$ = 0; }
661                 |       qualifiers
662                 ;
663
664 qualifier       :       RESTRICT
665                         { $$ = QUAL_RESTRICT; }
666                 |       VOLATILE_KEYWORD
667                         { $$ = QUAL_VOLATILE; }
668                 |       CONST_KEYWORD
669                         { $$ = QUAL_CONST; }
670                 ;
671
672 qualifiers      :       qualifier
673                 |       qualifier qualifiers
674                         { $$ = $1 | $2; }
675                 ;
676
677 /* This accepts all sorts of invalid constructions and produces
678    invalid output for them - an error would be better.  */
679
680 int_part        :       INT_KEYWORD
681                         { $$ = 0; }
682                 |       SIGNED_KEYWORD
683                         { $$ = INT_SIGNED; }
684                 |       UNSIGNED
685                         { $$ = INT_UNSIGNED; }
686                 |       CHAR
687                         { $$ = INT_CHAR; }
688                 |       LONG
689                         { $$ = INT_LONG; }
690                 |       SHORT
691                         { $$ = INT_SHORT; }
692                 ;
693
694 int_seq         :       int_part
695                 |       int_seq int_part
696                         { $$ = $1 | $2; if ($1 & $2 & INT_LONG) $$ = $1 | INT_LLONG; }
697                 ;
698
699 builtin_type    :       int_seq
700                         { $$ = d_int_type (state, $1); }
701                 |       FLOAT_KEYWORD
702                         { $$ = make_builtin_type (state, "float"); }
703                 |       DOUBLE_KEYWORD
704                         { $$ = make_builtin_type (state, "double"); }
705                 |       LONG DOUBLE_KEYWORD
706                         { $$ = make_builtin_type (state, "long double"); }
707                 |       BOOL
708                         { $$ = make_builtin_type (state, "bool"); }
709                 |       WCHAR_T
710                         { $$ = make_builtin_type (state, "wchar_t"); }
711                 |       VOID
712                         { $$ = make_builtin_type (state, "void"); }
713                 ;
714
715 ptr_operator    :       '*' qualifiers_opt
716                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_POINTER, NULL, NULL);
717                           $$.last = &d_left ($$.comp);
718                           $$.comp = d_qualify (state, $$.comp, $2, 0); }
719                 /* g++ seems to allow qualifiers after the reference?  */
720                 |       '&'
721                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_REFERENCE, NULL, NULL);
722                           $$.last = &d_left ($$.comp); }
723                 |       ANDAND
724                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_RVALUE_REFERENCE, NULL, NULL);
725                           $$.last = &d_left ($$.comp); }
726                 |       nested_name '*' qualifiers_opt
727                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_PTRMEM_TYPE, $1.comp, NULL);
728                           /* Convert the innermost DEMANGLE_COMPONENT_QUAL_NAME to a DEMANGLE_COMPONENT_NAME.  */
729                           *$1.last = *d_left ($1.last);
730                           $$.last = &d_right ($$.comp);
731                           $$.comp = d_qualify (state, $$.comp, $3, 0); }
732                 |       COLONCOLON nested_name '*' qualifiers_opt
733                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_PTRMEM_TYPE, $2.comp, NULL);
734                           /* Convert the innermost DEMANGLE_COMPONENT_QUAL_NAME to a DEMANGLE_COMPONENT_NAME.  */
735                           *$2.last = *d_left ($2.last);
736                           $$.last = &d_right ($$.comp);
737                           $$.comp = d_qualify (state, $$.comp, $4, 0); }
738                 ;
739
740 array_indicator :       '[' ']'
741                         { $$ = fill_comp (state, DEMANGLE_COMPONENT_ARRAY_TYPE, NULL, NULL); }
742                 |       '[' INT ']'
743                         { $$ = fill_comp (state, DEMANGLE_COMPONENT_ARRAY_TYPE, $2, NULL); }
744                 ;
745
746 /* Details of this approach inspired by the G++ < 3.4 parser.  */
747
748 /* This rule is only used in typespec_2, and expanded inline there for
749    efficiency.  */
750 /*
751 typespec        :       builtin_type
752                 |       colon_name
753                 ;
754 */
755
756 typespec_2      :       builtin_type qualifiers
757                         { $$ = d_qualify (state, $1, $2, 0); }
758                 |       builtin_type
759                 |       qualifiers builtin_type qualifiers
760                         { $$ = d_qualify (state, $2, $1 | $3, 0); }
761                 |       qualifiers builtin_type
762                         { $$ = d_qualify (state, $2, $1, 0); }
763
764                 |       name qualifiers
765                         { $$ = d_qualify (state, $1, $2, 0); }
766                 |       name
767                 |       qualifiers name qualifiers
768                         { $$ = d_qualify (state, $2, $1 | $3, 0); }
769                 |       qualifiers name
770                         { $$ = d_qualify (state, $2, $1, 0); }
771
772                 |       COLONCOLON name qualifiers
773                         { $$ = d_qualify (state, $2, $3, 0); }
774                 |       COLONCOLON name
775                         { $$ = $2; }
776                 |       qualifiers COLONCOLON name qualifiers
777                         { $$ = d_qualify (state, $3, $1 | $4, 0); }
778                 |       qualifiers COLONCOLON name
779                         { $$ = d_qualify (state, $3, $1, 0); }
780                 ;
781
782 abstract_declarator
783                 :       ptr_operator
784                         { $$.comp = $1.comp; $$.last = $1.last;
785                           $$.fn.comp = NULL; $$.fn.last = NULL; }
786                 |       ptr_operator abstract_declarator
787                         { $$ = $2; $$.fn.comp = NULL; $$.fn.last = NULL;
788                           if ($2.fn.comp) { $$.last = $2.fn.last; *$2.last = $2.fn.comp; }
789                           *$$.last = $1.comp;
790                           $$.last = $1.last; }
791                 |       direct_abstract_declarator
792                         { $$.fn.comp = NULL; $$.fn.last = NULL;
793                           if ($1.fn.comp) { $$.last = $1.fn.last; *$1.last = $1.fn.comp; }
794                         }
795                 ;
796
797 direct_abstract_declarator
798                 :       '(' abstract_declarator ')'
799                         { $$ = $2; $$.fn.comp = NULL; $$.fn.last = NULL; $$.fold_flag = 1;
800                           if ($2.fn.comp) { $$.last = $2.fn.last; *$2.last = $2.fn.comp; }
801                         }
802                 |       direct_abstract_declarator function_arglist
803                         { $$.fold_flag = 0;
804                           if ($1.fn.comp) { $$.last = $1.fn.last; *$1.last = $1.fn.comp; }
805                           if ($1.fold_flag)
806                             {
807                               *$$.last = $2.comp;
808                               $$.last = $2.last;
809                             }
810                           else
811                             $$.fn = $2;
812                         }
813                 |       direct_abstract_declarator array_indicator
814                         { $$.fn.comp = NULL; $$.fn.last = NULL; $$.fold_flag = 0;
815                           if ($1.fn.comp) { $$.last = $1.fn.last; *$1.last = $1.fn.comp; }
816                           *$1.last = $2;
817                           $$.last = &d_right ($2);
818                         }
819                 |       array_indicator
820                         { $$.fn.comp = NULL; $$.fn.last = NULL; $$.fold_flag = 0;
821                           $$.comp = $1;
822                           $$.last = &d_right ($1);
823                         }
824                 /* G++ has the following except for () and (type).  Then
825                    (type) is handled in regcast_or_absdcl and () is handled
826                    in fcast_or_absdcl.
827
828                    However, this is only useful for function types, and
829                    generates reduce/reduce conflicts with direct_declarator.
830                    We're interested in pointer-to-function types, and in
831                    functions, but not in function types - so leave this
832                    out.  */
833                 /* |    function_arglist */
834                 ;
835
836 abstract_declarator_fn
837                 :       ptr_operator
838                         { $$.comp = $1.comp; $$.last = $1.last;
839                           $$.fn.comp = NULL; $$.fn.last = NULL; $$.start = NULL; }
840                 |       ptr_operator abstract_declarator_fn
841                         { $$ = $2;
842                           if ($2.last)
843                             *$$.last = $1.comp;
844                           else
845                             $$.comp = $1.comp;
846                           $$.last = $1.last;
847                         }
848                 |       direct_abstract_declarator
849                         { $$.comp = $1.comp; $$.last = $1.last; $$.fn = $1.fn; $$.start = NULL; }
850                 |       direct_abstract_declarator function_arglist COLONCOLON start
851                         { $$.start = $4;
852                           if ($1.fn.comp) { $$.last = $1.fn.last; *$1.last = $1.fn.comp; }
853                           if ($1.fold_flag)
854                             {
855                               *$$.last = $2.comp;
856                               $$.last = $2.last;
857                             }
858                           else
859                             $$.fn = $2;
860                         }
861                 |       function_arglist start_opt
862                         { $$.fn = $1;
863                           $$.start = $2;
864                           $$.comp = NULL; $$.last = NULL;
865                         }
866                 ;
867
868 type            :       typespec_2
869                 |       typespec_2 abstract_declarator
870                         { $$ = $2.comp;
871                           *$2.last = $1;
872                         }
873                 ;
874
875 declarator      :       ptr_operator declarator
876                         { $$.comp = $2.comp;
877                           $$.last = $1.last;
878                           *$2.last = $1.comp; }
879                 |       direct_declarator
880                 ;
881
882 direct_declarator
883                 :       '(' declarator ')'
884                         { $$ = $2; }
885                 |       direct_declarator function_arglist
886                         { $$.comp = $1.comp;
887                           *$1.last = $2.comp;
888                           $$.last = $2.last;
889                         }
890                 |       direct_declarator array_indicator
891                         { $$.comp = $1.comp;
892                           *$1.last = $2;
893                           $$.last = &d_right ($2);
894                         }
895                 |       colon_ext_name
896                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_TYPED_NAME, $1, NULL);
897                           $$.last = &d_right ($$.comp);
898                         }
899                 ;
900
901 /* These are similar to declarator and direct_declarator except that they
902    do not permit ( colon_ext_name ), which is ambiguous with a function
903    argument list.  They also don't permit a few other forms with redundant
904    parentheses around the colon_ext_name; any colon_ext_name in parentheses
905    must be followed by an argument list or an array indicator, or preceded
906    by a pointer.  */
907 declarator_1    :       ptr_operator declarator_1
908                         { $$.comp = $2.comp;
909                           $$.last = $1.last;
910                           *$2.last = $1.comp; }
911                 |       colon_ext_name
912                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_TYPED_NAME, $1, NULL);
913                           $$.last = &d_right ($$.comp);
914                         }
915                 |       direct_declarator_1
916
917                         /* Function local variable or type.  The typespec to
918                            our left is the type of the containing function. 
919                            This should be OK, because function local types
920                            can not be templates, so the return types of their
921                            members will not be mangled.  If they are hopefully
922                            they'll end up to the right of the ::.  */
923                 |       colon_ext_name function_arglist COLONCOLON start
924                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_TYPED_NAME, $1, $2.comp);
925                           $$.last = $2.last;
926                           $$.comp = fill_comp (state, DEMANGLE_COMPONENT_LOCAL_NAME, $$.comp, $4);
927                         }
928                 |       direct_declarator_1 function_arglist COLONCOLON start
929                         { $$.comp = $1.comp;
930                           *$1.last = $2.comp;
931                           $$.last = $2.last;
932                           $$.comp = fill_comp (state, DEMANGLE_COMPONENT_LOCAL_NAME, $$.comp, $4);
933                         }
934                 ;
935
936 direct_declarator_1
937                 :       '(' ptr_operator declarator ')'
938                         { $$.comp = $3.comp;
939                           $$.last = $2.last;
940                           *$3.last = $2.comp; }
941                 |       direct_declarator_1 function_arglist
942                         { $$.comp = $1.comp;
943                           *$1.last = $2.comp;
944                           $$.last = $2.last;
945                         }
946                 |       direct_declarator_1 array_indicator
947                         { $$.comp = $1.comp;
948                           *$1.last = $2;
949                           $$.last = &d_right ($2);
950                         }
951                 |       colon_ext_name function_arglist
952                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_TYPED_NAME, $1, $2.comp);
953                           $$.last = $2.last;
954                         }
955                 |       colon_ext_name array_indicator
956                         { $$.comp = fill_comp (state, DEMANGLE_COMPONENT_TYPED_NAME, $1, $2);
957                           $$.last = &d_right ($2);
958                         }
959                 ;
960
961 exp     :       '(' exp1 ')'
962                 { $$ = $2; }
963         ;
964
965 /* Silly trick.  Only allow '>' when parenthesized, in order to
966    handle conflict with templates.  */
967 exp1    :       exp
968         ;
969
970 exp1    :       exp '>' exp
971                 { $$ = d_binary (state, ">", $1, $3); }
972         ;
973
974 /* References.  Not allowed everywhere in template parameters, only
975    at the top level, but treat them as expressions in case they are wrapped
976    in parentheses.  */
977 exp1    :       '&' start
978                 { $$ = fill_comp (state, DEMANGLE_COMPONENT_UNARY, make_operator (state, "&", 1), $2); }
979         |       '&' '(' start ')'
980                 { $$ = fill_comp (state, DEMANGLE_COMPONENT_UNARY, make_operator (state, "&", 1), $3); }
981         ;
982
983 /* Expressions, not including the comma operator.  */
984 exp     :       '-' exp    %prec UNARY
985                 { $$ = d_unary (state, "-", $2); }
986         ;
987
988 exp     :       '!' exp    %prec UNARY
989                 { $$ = d_unary (state, "!", $2); }
990         ;
991
992 exp     :       '~' exp    %prec UNARY
993                 { $$ = d_unary (state, "~", $2); }
994         ;
995
996 /* Casts.  First your normal C-style cast.  If exp is a LITERAL, just change
997    its type.  */
998
999 exp     :       '(' type ')' exp  %prec UNARY
1000                 { if ($4->type == DEMANGLE_COMPONENT_LITERAL
1001                       || $4->type == DEMANGLE_COMPONENT_LITERAL_NEG)
1002                     {
1003                       $$ = $4;
1004                       d_left ($4) = $2;
1005                     }
1006                   else
1007                     $$ = fill_comp (state, DEMANGLE_COMPONENT_UNARY,
1008                                       fill_comp (state, DEMANGLE_COMPONENT_CAST, $2, NULL),
1009                                       $4);
1010                 }
1011         ;
1012
1013 /* Mangling does not differentiate between these, so we don't need to
1014    either.  */
1015 exp     :       STATIC_CAST '<' type '>' '(' exp1 ')' %prec UNARY
1016                 { $$ = fill_comp (state, DEMANGLE_COMPONENT_UNARY,
1017                                     fill_comp (state, DEMANGLE_COMPONENT_CAST, $3, NULL),
1018                                     $6);
1019                 }
1020         ;
1021
1022 exp     :       DYNAMIC_CAST '<' type '>' '(' exp1 ')' %prec UNARY
1023                 { $$ = fill_comp (state, DEMANGLE_COMPONENT_UNARY,
1024                                     fill_comp (state, DEMANGLE_COMPONENT_CAST, $3, NULL),
1025                                     $6);
1026                 }
1027         ;
1028
1029 exp     :       REINTERPRET_CAST '<' type '>' '(' exp1 ')' %prec UNARY
1030                 { $$ = fill_comp (state, DEMANGLE_COMPONENT_UNARY,
1031                                     fill_comp (state, DEMANGLE_COMPONENT_CAST, $3, NULL),
1032                                     $6);
1033                 }
1034         ;
1035
1036 /* Another form of C++-style cast is "type ( exp1 )".  This creates too many
1037    conflicts to support.  For a while we supported the simpler
1038    "typespec_2 ( exp1 )", but that conflicts with "& ( start )" as a
1039    reference, deep within the wilderness of abstract declarators:
1040    Qux<int(&(*))> vs Qux<int(&(var))>, a shift-reduce conflict at the
1041    innermost left parenthesis.  So we do not support function-like casts.
1042    Fortunately they never appear in demangler output.  */
1043
1044 /* TO INVESTIGATE: ._0 style anonymous names; anonymous namespaces */
1045
1046 /* Binary operators in order of decreasing precedence.  */
1047
1048 exp     :       exp '*' exp
1049                 { $$ = d_binary (state, "*", $1, $3); }
1050         ;
1051
1052 exp     :       exp '/' exp
1053                 { $$ = d_binary (state, "/", $1, $3); }
1054         ;
1055
1056 exp     :       exp '%' exp
1057                 { $$ = d_binary (state, "%", $1, $3); }
1058         ;
1059
1060 exp     :       exp '+' exp
1061                 { $$ = d_binary (state, "+", $1, $3); }
1062         ;
1063
1064 exp     :       exp '-' exp
1065                 { $$ = d_binary (state, "-", $1, $3); }
1066         ;
1067
1068 exp     :       exp LSH exp
1069                 { $$ = d_binary (state, "<<", $1, $3); }
1070         ;
1071
1072 exp     :       exp RSH exp
1073                 { $$ = d_binary (state, ">>", $1, $3); }
1074         ;
1075
1076 exp     :       exp EQUAL exp
1077                 { $$ = d_binary (state, "==", $1, $3); }
1078         ;
1079
1080 exp     :       exp NOTEQUAL exp
1081                 { $$ = d_binary (state, "!=", $1, $3); }
1082         ;
1083
1084 exp     :       exp LEQ exp
1085                 { $$ = d_binary (state, "<=", $1, $3); }
1086         ;
1087
1088 exp     :       exp GEQ exp
1089                 { $$ = d_binary (state, ">=", $1, $3); }
1090         ;
1091
1092 exp     :       exp '<' exp
1093                 { $$ = d_binary (state, "<", $1, $3); }
1094         ;
1095
1096 exp     :       exp '&' exp
1097                 { $$ = d_binary (state, "&", $1, $3); }
1098         ;
1099
1100 exp     :       exp '^' exp
1101                 { $$ = d_binary (state, "^", $1, $3); }
1102         ;
1103
1104 exp     :       exp '|' exp
1105                 { $$ = d_binary (state, "|", $1, $3); }
1106         ;
1107
1108 exp     :       exp ANDAND exp
1109                 { $$ = d_binary (state, "&&", $1, $3); }
1110         ;
1111
1112 exp     :       exp OROR exp
1113                 { $$ = d_binary (state, "||", $1, $3); }
1114         ;
1115
1116 /* Not 100% sure these are necessary, but they're harmless.  */
1117 exp     :       exp ARROW NAME
1118                 { $$ = d_binary (state, "->", $1, $3); }
1119         ;
1120
1121 exp     :       exp '.' NAME
1122                 { $$ = d_binary (state, ".", $1, $3); }
1123         ;
1124
1125 exp     :       exp '?' exp ':' exp     %prec '?'
1126                 { $$ = fill_comp (state, DEMANGLE_COMPONENT_TRINARY, make_operator (state, "?", 3),
1127                                     fill_comp (state, DEMANGLE_COMPONENT_TRINARY_ARG1, $1,
1128                                                  fill_comp (state, DEMANGLE_COMPONENT_TRINARY_ARG2, $3, $5)));
1129                 }
1130         ;
1131                           
1132 exp     :       INT
1133         ;
1134
1135 /* Not generally allowed.  */
1136 exp     :       FLOAT
1137         ;
1138
1139 exp     :       SIZEOF '(' type ')'     %prec UNARY
1140                 {
1141                   /* Match the whitespacing of cplus_demangle_operators.
1142                      It would abort on unrecognized string otherwise.  */
1143                   $$ = d_unary (state, "sizeof ", $3);
1144                 }
1145         ;
1146
1147 /* C++.  */
1148 exp     :       TRUEKEYWORD    
1149                 { struct demangle_component *i;
1150                   i = make_name (state, "1", 1);
1151                   $$ = fill_comp (state, DEMANGLE_COMPONENT_LITERAL,
1152                                     make_builtin_type (state, "bool"),
1153                                     i);
1154                 }
1155         ;
1156
1157 exp     :       FALSEKEYWORD   
1158                 { struct demangle_component *i;
1159                   i = make_name (state, "0", 1);
1160                   $$ = fill_comp (state, DEMANGLE_COMPONENT_LITERAL,
1161                                     make_builtin_type (state, "bool"),
1162                                     i);
1163                 }
1164         ;
1165
1166 /* end of C++.  */
1167
1168 %%
1169
1170 /* Apply QUALIFIERS to LHS and return a qualified component.  IS_METHOD
1171    is set if LHS is a method, in which case the qualifiers are logically
1172    applied to "this".  We apply qualifiers in a consistent order; LHS
1173    may already be qualified; duplicate qualifiers are not created.  */
1174
1175 struct demangle_component *
1176 d_qualify (cpname_state *state, struct demangle_component *lhs, int qualifiers,
1177            int is_method)
1178 {
1179   struct demangle_component **inner_p;
1180   enum demangle_component_type type;
1181
1182   /* For now the order is CONST (innermost), VOLATILE, RESTRICT.  */
1183
1184 #define HANDLE_QUAL(TYPE, MTYPE, QUAL)                          \
1185   if ((qualifiers & QUAL) && (type != TYPE) && (type != MTYPE)) \
1186     {                                                           \
1187       *inner_p = fill_comp (state, is_method ? MTYPE : TYPE,    \
1188                               *inner_p, NULL);                  \
1189       inner_p = &d_left (*inner_p);                             \
1190       type = (*inner_p)->type;                                  \
1191     }                                                           \
1192   else if (type == TYPE || type == MTYPE)                       \
1193     {                                                           \
1194       inner_p = &d_left (*inner_p);                             \
1195       type = (*inner_p)->type;                                  \
1196     }
1197
1198   inner_p = &lhs;
1199
1200   type = (*inner_p)->type;
1201
1202   HANDLE_QUAL (DEMANGLE_COMPONENT_RESTRICT, DEMANGLE_COMPONENT_RESTRICT_THIS, QUAL_RESTRICT);
1203   HANDLE_QUAL (DEMANGLE_COMPONENT_VOLATILE, DEMANGLE_COMPONENT_VOLATILE_THIS, QUAL_VOLATILE);
1204   HANDLE_QUAL (DEMANGLE_COMPONENT_CONST, DEMANGLE_COMPONENT_CONST_THIS, QUAL_CONST);
1205
1206   return lhs;
1207 }
1208
1209 /* Return a builtin type corresponding to FLAGS.  */
1210
1211 static struct demangle_component *
1212 d_int_type (cpname_state *state, int flags)
1213 {
1214   const char *name;
1215
1216   switch (flags)
1217     {
1218     case INT_SIGNED | INT_CHAR:
1219       name = "signed char";
1220       break;
1221     case INT_CHAR:
1222       name = "char";
1223       break;
1224     case INT_UNSIGNED | INT_CHAR:
1225       name = "unsigned char";
1226       break;
1227     case 0:
1228     case INT_SIGNED:
1229       name = "int";
1230       break;
1231     case INT_UNSIGNED:
1232       name = "unsigned int";
1233       break;
1234     case INT_LONG:
1235     case INT_SIGNED | INT_LONG:
1236       name = "long";
1237       break;
1238     case INT_UNSIGNED | INT_LONG:
1239       name = "unsigned long";
1240       break;
1241     case INT_SHORT:
1242     case INT_SIGNED | INT_SHORT:
1243       name = "short";
1244       break;
1245     case INT_UNSIGNED | INT_SHORT:
1246       name = "unsigned short";
1247       break;
1248     case INT_LLONG | INT_LONG:
1249     case INT_SIGNED | INT_LLONG | INT_LONG:
1250       name = "long long";
1251       break;
1252     case INT_UNSIGNED | INT_LLONG | INT_LONG:
1253       name = "unsigned long long";
1254       break;
1255     default:
1256       return NULL;
1257     }
1258
1259   return make_builtin_type (state, name);
1260 }
1261
1262 /* Wrapper to create a unary operation.  */
1263
1264 static struct demangle_component *
1265 d_unary (cpname_state *state, const char *name, struct demangle_component *lhs)
1266 {
1267   return fill_comp (state, DEMANGLE_COMPONENT_UNARY, make_operator (state, name, 1), lhs);
1268 }
1269
1270 /* Wrapper to create a binary operation.  */
1271
1272 static struct demangle_component *
1273 d_binary (cpname_state *state, const char *name, struct demangle_component *lhs,
1274           struct demangle_component *rhs)
1275 {
1276   return fill_comp (state, DEMANGLE_COMPONENT_BINARY, make_operator (state, name, 2),
1277                       fill_comp (state, DEMANGLE_COMPONENT_BINARY_ARGS, lhs, rhs));
1278 }
1279
1280 /* Find the end of a symbol name starting at LEXPTR.  */
1281
1282 static const char *
1283 symbol_end (const char *lexptr)
1284 {
1285   const char *p = lexptr;
1286
1287   while (*p && (c_ident_is_alnum (*p) || *p == '_' || *p == '$' || *p == '.'))
1288     p++;
1289
1290   return p;
1291 }
1292
1293 /* Take care of parsing a number (anything that starts with a digit).
1294    The number starts at P and contains LEN characters.  Store the result in
1295    YYLVAL.  */
1296
1297 static int
1298 parse_number (cpname_state *state, const char *p, int len, int parsed_float,
1299               YYSTYPE *lvalp)
1300 {
1301   int unsigned_p = 0;
1302
1303   /* Number of "L" suffixes encountered.  */
1304   int long_p = 0;
1305
1306   struct demangle_component *signed_type;
1307   struct demangle_component *unsigned_type;
1308   struct demangle_component *type, *name;
1309   enum demangle_component_type literal_type;
1310
1311   if (p[0] == '-')
1312     {
1313       literal_type = DEMANGLE_COMPONENT_LITERAL_NEG;
1314       p++;
1315       len--;
1316     }
1317   else
1318     literal_type = DEMANGLE_COMPONENT_LITERAL;
1319
1320   if (parsed_float)
1321     {
1322       /* It's a float since it contains a point or an exponent.  */
1323       char c;
1324
1325       /* The GDB lexer checks the result of scanf at this point.  Not doing
1326          this leaves our error checking slightly weaker but only for invalid
1327          data.  */
1328
1329       /* See if it has `f' or `l' suffix (float or long double).  */
1330
1331       c = TOLOWER (p[len - 1]);
1332
1333       if (c == 'f')
1334         {
1335           len--;
1336           type = make_builtin_type (state, "float");
1337         }
1338       else if (c == 'l')
1339         {
1340           len--;
1341           type = make_builtin_type (state, "long double");
1342         }
1343       else if (ISDIGIT (c) || c == '.')
1344         type = make_builtin_type (state, "double");
1345       else
1346         return ERROR;
1347
1348       name = make_name (state, p, len);
1349       lvalp->comp = fill_comp (state, literal_type, type, name);
1350
1351       return FLOAT;
1352     }
1353
1354   /* This treats 0x1 and 1 as different literals.  We also do not
1355      automatically generate unsigned types.  */
1356
1357   long_p = 0;
1358   unsigned_p = 0;
1359   while (len > 0)
1360     {
1361       if (p[len - 1] == 'l' || p[len - 1] == 'L')
1362         {
1363           len--;
1364           long_p++;
1365           continue;
1366         }
1367       if (p[len - 1] == 'u' || p[len - 1] == 'U')
1368         {
1369           len--;
1370           unsigned_p++;
1371           continue;
1372         }
1373       break;
1374     }
1375
1376   if (long_p == 0)
1377     {
1378       unsigned_type = make_builtin_type (state, "unsigned int");
1379       signed_type = make_builtin_type (state, "int");
1380     }
1381   else if (long_p == 1)
1382     {
1383       unsigned_type = make_builtin_type (state, "unsigned long");
1384       signed_type = make_builtin_type (state, "long");
1385     }
1386   else
1387     {
1388       unsigned_type = make_builtin_type (state, "unsigned long long");
1389       signed_type = make_builtin_type (state, "long long");
1390     }
1391
1392    if (unsigned_p)
1393      type = unsigned_type;
1394    else
1395      type = signed_type;
1396
1397    name = make_name (state, p, len);
1398    lvalp->comp = fill_comp (state, literal_type, type, name);
1399
1400    return INT;
1401 }
1402
1403 static char backslashable[] = "abefnrtv";
1404 static char represented[] = "\a\b\e\f\n\r\t\v";
1405
1406 /* Translate the backslash the way we would in the host character set.  */
1407 static int
1408 c_parse_backslash (int host_char, int *target_char)
1409 {
1410   const char *ix;
1411   ix = strchr (backslashable, host_char);
1412   if (! ix)
1413     return 0;
1414   else
1415     *target_char = represented[ix - backslashable];
1416   return 1;
1417 }
1418
1419 /* Parse a C escape sequence.  STRING_PTR points to a variable
1420    containing a pointer to the string to parse.  That pointer
1421    should point to the character after the \.  That pointer
1422    is updated past the characters we use.  The value of the
1423    escape sequence is returned.
1424
1425    A negative value means the sequence \ newline was seen,
1426    which is supposed to be equivalent to nothing at all.
1427
1428    If \ is followed by a null character, we return a negative
1429    value and leave the string pointer pointing at the null character.
1430
1431    If \ is followed by 000, we return 0 and leave the string pointer
1432    after the zeros.  A value of 0 does not mean end of string.  */
1433
1434 static int
1435 cp_parse_escape (const char **string_ptr)
1436 {
1437   int target_char;
1438   int c = *(*string_ptr)++;
1439   if (c_parse_backslash (c, &target_char))
1440     return target_char;
1441   else
1442     switch (c)
1443       {
1444       case '\n':
1445         return -2;
1446       case 0:
1447         (*string_ptr)--;
1448         return 0;
1449       case '^':
1450         {
1451           c = *(*string_ptr)++;
1452
1453           if (c == '?')
1454             return 0177;
1455           else if (c == '\\')
1456             target_char = cp_parse_escape (string_ptr);
1457           else
1458             target_char = c;
1459
1460           /* Now target_char is something like `c', and we want to find
1461              its control-character equivalent.  */
1462           target_char = target_char & 037;
1463
1464           return target_char;
1465         }
1466
1467       case '0':
1468       case '1':
1469       case '2':
1470       case '3':
1471       case '4':
1472       case '5':
1473       case '6':
1474       case '7':
1475         {
1476           int i = c - '0';
1477           int count = 0;
1478           while (++count < 3)
1479             {
1480               c = (**string_ptr);
1481               if (c >= '0' && c <= '7')
1482                 {
1483                   (*string_ptr)++;
1484                   i *= 8;
1485                   i += c - '0';
1486                 }
1487               else
1488                 {
1489                   break;
1490                 }
1491             }
1492           return i;
1493         }
1494       default:
1495         return c;
1496       }
1497 }
1498
1499 #define HANDLE_SPECIAL(string, comp)                            \
1500   if (strncmp (tokstart, string, sizeof (string) - 1) == 0)     \
1501     {                                                           \
1502       state->lexptr = tokstart + sizeof (string) - 1;                   \
1503       lvalp->lval = comp;                                       \
1504       return DEMANGLER_SPECIAL;                                 \
1505     }
1506
1507 #define HANDLE_TOKEN2(string, token)                    \
1508   if (state->lexptr[1] == string[1])                            \
1509     {                                                   \
1510       state->lexptr += 2;                                       \
1511       lvalp->opname = string;                           \
1512       return token;                                     \
1513     }      
1514
1515 #define HANDLE_TOKEN3(string, token)                    \
1516   if (state->lexptr[1] == string[1] && state->lexptr[2] == string[2])   \
1517     {                                                   \
1518       state->lexptr += 3;                                       \
1519       lvalp->opname = string;                           \
1520       return token;                                     \
1521     }      
1522
1523 /* Read one token, getting characters through LEXPTR.  */
1524
1525 static int
1526 yylex (YYSTYPE *lvalp, cpname_state *state)
1527 {
1528   int c;
1529   int namelen;
1530   const char *tokstart;
1531
1532  retry:
1533   state->prev_lexptr = state->lexptr;
1534   tokstart = state->lexptr;
1535
1536   switch (c = *tokstart)
1537     {
1538     case 0:
1539       return 0;
1540
1541     case ' ':
1542     case '\t':
1543     case '\n':
1544       state->lexptr++;
1545       goto retry;
1546
1547     case '\'':
1548       /* We either have a character constant ('0' or '\177' for example)
1549          or we have a quoted symbol reference ('foo(int,int)' in C++
1550          for example). */
1551       state->lexptr++;
1552       c = *state->lexptr++;
1553       if (c == '\\')
1554         c = cp_parse_escape (&state->lexptr);
1555       else if (c == '\'')
1556         {
1557           yyerror (state, _("empty character constant"));
1558           return ERROR;
1559         }
1560
1561       c = *state->lexptr++;
1562       if (c != '\'')
1563         {
1564           yyerror (state, _("invalid character constant"));
1565           return ERROR;
1566         }
1567
1568       /* FIXME: We should refer to a canonical form of the character,
1569          presumably the same one that appears in manglings - the decimal
1570          representation.  But if that isn't in our input then we have to
1571          allocate memory for it somewhere.  */
1572       lvalp->comp = fill_comp (state, DEMANGLE_COMPONENT_LITERAL,
1573                                  make_builtin_type (state, "char"),
1574                                  make_name (state, tokstart, state->lexptr - tokstart));
1575
1576       return INT;
1577
1578     case '(':
1579       if (strncmp (tokstart, "(anonymous namespace)", 21) == 0)
1580         {
1581           state->lexptr += 21;
1582           lvalp->comp = make_name (state, "(anonymous namespace)",
1583                                      sizeof "(anonymous namespace)" - 1);
1584           return NAME;
1585         }
1586         /* FALL THROUGH */
1587
1588     case ')':
1589     case ',':
1590       state->lexptr++;
1591       return c;
1592
1593     case '.':
1594       if (state->lexptr[1] == '.' && state->lexptr[2] == '.')
1595         {
1596           state->lexptr += 3;
1597           return ELLIPSIS;
1598         }
1599
1600       /* Might be a floating point number.  */
1601       if (state->lexptr[1] < '0' || state->lexptr[1] > '9')
1602         goto symbol;            /* Nope, must be a symbol. */
1603
1604       goto try_number;
1605
1606     case '-':
1607       HANDLE_TOKEN2 ("-=", ASSIGN_MODIFY);
1608       HANDLE_TOKEN2 ("--", DECREMENT);
1609       HANDLE_TOKEN2 ("->", ARROW);
1610
1611       /* For construction vtables.  This is kind of hokey.  */
1612       if (strncmp (tokstart, "-in-", 4) == 0)
1613         {
1614           state->lexptr += 4;
1615           return CONSTRUCTION_IN;
1616         }
1617
1618       if (state->lexptr[1] < '0' || state->lexptr[1] > '9')
1619         {
1620           state->lexptr++;
1621           return '-';
1622         }
1623       /* FALL THRU.  */
1624
1625     try_number:
1626     case '0':
1627     case '1':
1628     case '2':
1629     case '3':
1630     case '4':
1631     case '5':
1632     case '6':
1633     case '7':
1634     case '8':
1635     case '9':
1636       {
1637         /* It's a number.  */
1638         int got_dot = 0, got_e = 0, toktype;
1639         const char *p = tokstart;
1640         int hex = 0;
1641
1642         if (c == '-')
1643           p++;
1644
1645         if (c == '0' && (p[1] == 'x' || p[1] == 'X'))
1646           {
1647             p += 2;
1648             hex = 1;
1649           }
1650         else if (c == '0' && (p[1]=='t' || p[1]=='T' || p[1]=='d' || p[1]=='D'))
1651           {
1652             p += 2;
1653             hex = 0;
1654           }
1655
1656         for (;; ++p)
1657           {
1658             /* This test includes !hex because 'e' is a valid hex digit
1659                and thus does not indicate a floating point number when
1660                the radix is hex.  */
1661             if (!hex && !got_e && (*p == 'e' || *p == 'E'))
1662               got_dot = got_e = 1;
1663             /* This test does not include !hex, because a '.' always indicates
1664                a decimal floating point number regardless of the radix.
1665
1666                NOTE drow/2005-03-09: This comment is not accurate in C99;
1667                however, it's not clear that all the floating point support
1668                in this file is doing any good here.  */
1669             else if (!got_dot && *p == '.')
1670               got_dot = 1;
1671             else if (got_e && (p[-1] == 'e' || p[-1] == 'E')
1672                      && (*p == '-' || *p == '+'))
1673               /* This is the sign of the exponent, not the end of the
1674                  number.  */
1675               continue;
1676             /* We will take any letters or digits.  parse_number will
1677                complain if past the radix, or if L or U are not final.  */
1678             else if (! ISALNUM (*p))
1679               break;
1680           }
1681         toktype = parse_number (state, tokstart, p - tokstart, got_dot|got_e,
1682                                 lvalp);
1683         if (toktype == ERROR)
1684           {
1685             char *err_copy = (char *) alloca (p - tokstart + 1);
1686
1687             memcpy (err_copy, tokstart, p - tokstart);
1688             err_copy[p - tokstart] = 0;
1689             yyerror (state, _("invalid number"));
1690             return ERROR;
1691           }
1692         state->lexptr = p;
1693         return toktype;
1694       }
1695
1696     case '+':
1697       HANDLE_TOKEN2 ("+=", ASSIGN_MODIFY);
1698       HANDLE_TOKEN2 ("++", INCREMENT);
1699       state->lexptr++;
1700       return c;
1701     case '*':
1702       HANDLE_TOKEN2 ("*=", ASSIGN_MODIFY);
1703       state->lexptr++;
1704       return c;
1705     case '/':
1706       HANDLE_TOKEN2 ("/=", ASSIGN_MODIFY);
1707       state->lexptr++;
1708       return c;
1709     case '%':
1710       HANDLE_TOKEN2 ("%=", ASSIGN_MODIFY);
1711       state->lexptr++;
1712       return c;
1713     case '|':
1714       HANDLE_TOKEN2 ("|=", ASSIGN_MODIFY);
1715       HANDLE_TOKEN2 ("||", OROR);
1716       state->lexptr++;
1717       return c;
1718     case '&':
1719       HANDLE_TOKEN2 ("&=", ASSIGN_MODIFY);
1720       HANDLE_TOKEN2 ("&&", ANDAND);
1721       state->lexptr++;
1722       return c;
1723     case '^':
1724       HANDLE_TOKEN2 ("^=", ASSIGN_MODIFY);
1725       state->lexptr++;
1726       return c;
1727     case '!':
1728       HANDLE_TOKEN2 ("!=", NOTEQUAL);
1729       state->lexptr++;
1730       return c;
1731     case '<':
1732       HANDLE_TOKEN3 ("<<=", ASSIGN_MODIFY);
1733       HANDLE_TOKEN2 ("<=", LEQ);
1734       HANDLE_TOKEN2 ("<<", LSH);
1735       state->lexptr++;
1736       return c;
1737     case '>':
1738       HANDLE_TOKEN3 (">>=", ASSIGN_MODIFY);
1739       HANDLE_TOKEN2 (">=", GEQ);
1740       HANDLE_TOKEN2 (">>", RSH);
1741       state->lexptr++;
1742       return c;
1743     case '=':
1744       HANDLE_TOKEN2 ("==", EQUAL);
1745       state->lexptr++;
1746       return c;
1747     case ':':
1748       HANDLE_TOKEN2 ("::", COLONCOLON);
1749       state->lexptr++;
1750       return c;
1751
1752     case '[':
1753     case ']':
1754     case '?':
1755     case '@':
1756     case '~':
1757     case '{':
1758     case '}':
1759     symbol:
1760       state->lexptr++;
1761       return c;
1762
1763     case '"':
1764       /* These can't occur in C++ names.  */
1765       yyerror (state, _("unexpected string literal"));
1766       return ERROR;
1767     }
1768
1769   if (!(c == '_' || c == '$' || c_ident_is_alpha (c)))
1770     {
1771       /* We must have come across a bad character (e.g. ';').  */
1772       yyerror (state, _("invalid character"));
1773       return ERROR;
1774     }
1775
1776   /* It's a name.  See how long it is.  */
1777   namelen = 0;
1778   do
1779     c = tokstart[++namelen];
1780   while (c_ident_is_alnum (c) || c == '_' || c == '$');
1781
1782   state->lexptr += namelen;
1783
1784   /* Catch specific keywords.  Notice that some of the keywords contain
1785      spaces, and are sorted by the length of the first word.  They must
1786      all include a trailing space in the string comparison.  */
1787   switch (namelen)
1788     {
1789     case 16:
1790       if (strncmp (tokstart, "reinterpret_cast", 16) == 0)
1791         return REINTERPRET_CAST;
1792       break;
1793     case 12:
1794       if (strncmp (tokstart, "construction vtable for ", 24) == 0)
1795         {
1796           state->lexptr = tokstart + 24;
1797           return CONSTRUCTION_VTABLE;
1798         }
1799       if (strncmp (tokstart, "dynamic_cast", 12) == 0)
1800         return DYNAMIC_CAST;
1801       break;
1802     case 11:
1803       if (strncmp (tokstart, "static_cast", 11) == 0)
1804         return STATIC_CAST;
1805       break;
1806     case 9:
1807       HANDLE_SPECIAL ("covariant return thunk to ", DEMANGLE_COMPONENT_COVARIANT_THUNK);
1808       HANDLE_SPECIAL ("reference temporary for ", DEMANGLE_COMPONENT_REFTEMP);
1809       break;
1810     case 8:
1811       HANDLE_SPECIAL ("typeinfo for ", DEMANGLE_COMPONENT_TYPEINFO);
1812       HANDLE_SPECIAL ("typeinfo fn for ", DEMANGLE_COMPONENT_TYPEINFO_FN);
1813       HANDLE_SPECIAL ("typeinfo name for ", DEMANGLE_COMPONENT_TYPEINFO_NAME);
1814       if (strncmp (tokstart, "operator", 8) == 0)
1815         return OPERATOR;
1816       if (strncmp (tokstart, "restrict", 8) == 0)
1817         return RESTRICT;
1818       if (strncmp (tokstart, "unsigned", 8) == 0)
1819         return UNSIGNED;
1820       if (strncmp (tokstart, "template", 8) == 0)
1821         return TEMPLATE;
1822       if (strncmp (tokstart, "volatile", 8) == 0)
1823         return VOLATILE_KEYWORD;
1824       break;
1825     case 7:
1826       HANDLE_SPECIAL ("virtual thunk to ", DEMANGLE_COMPONENT_VIRTUAL_THUNK);
1827       if (strncmp (tokstart, "wchar_t", 7) == 0)
1828         return WCHAR_T;
1829       break;
1830     case 6:
1831       if (strncmp (tokstart, "global constructors keyed to ", 29) == 0)
1832         {
1833           const char *p;
1834           state->lexptr = tokstart + 29;
1835           lvalp->lval = DEMANGLE_COMPONENT_GLOBAL_CONSTRUCTORS;
1836           /* Find the end of the symbol.  */
1837           p = symbol_end (state->lexptr);
1838           lvalp->comp = make_name (state, state->lexptr, p - state->lexptr);
1839           state->lexptr = p;
1840           return DEMANGLER_SPECIAL;
1841         }
1842       if (strncmp (tokstart, "global destructors keyed to ", 28) == 0)
1843         {
1844           const char *p;
1845           state->lexptr = tokstart + 28;
1846           lvalp->lval = DEMANGLE_COMPONENT_GLOBAL_DESTRUCTORS;
1847           /* Find the end of the symbol.  */
1848           p = symbol_end (state->lexptr);
1849           lvalp->comp = make_name (state, state->lexptr, p - state->lexptr);
1850           state->lexptr = p;
1851           return DEMANGLER_SPECIAL;
1852         }
1853
1854       HANDLE_SPECIAL ("vtable for ", DEMANGLE_COMPONENT_VTABLE);
1855       if (strncmp (tokstart, "delete", 6) == 0)
1856         return DELETE;
1857       if (strncmp (tokstart, "struct", 6) == 0)
1858         return STRUCT;
1859       if (strncmp (tokstart, "signed", 6) == 0)
1860         return SIGNED_KEYWORD;
1861       if (strncmp (tokstart, "sizeof", 6) == 0)
1862         return SIZEOF;
1863       if (strncmp (tokstart, "double", 6) == 0)
1864         return DOUBLE_KEYWORD;
1865       break;
1866     case 5:
1867       HANDLE_SPECIAL ("guard variable for ", DEMANGLE_COMPONENT_GUARD);
1868       if (strncmp (tokstart, "false", 5) == 0)
1869         return FALSEKEYWORD;
1870       if (strncmp (tokstart, "class", 5) == 0)
1871         return CLASS;
1872       if (strncmp (tokstart, "union", 5) == 0)
1873         return UNION;
1874       if (strncmp (tokstart, "float", 5) == 0)
1875         return FLOAT_KEYWORD;
1876       if (strncmp (tokstart, "short", 5) == 0)
1877         return SHORT;
1878       if (strncmp (tokstart, "const", 5) == 0)
1879         return CONST_KEYWORD;
1880       break;
1881     case 4:
1882       if (strncmp (tokstart, "void", 4) == 0)
1883         return VOID;
1884       if (strncmp (tokstart, "bool", 4) == 0)
1885         return BOOL;
1886       if (strncmp (tokstart, "char", 4) == 0)
1887         return CHAR;
1888       if (strncmp (tokstart, "enum", 4) == 0)
1889         return ENUM;
1890       if (strncmp (tokstart, "long", 4) == 0)
1891         return LONG;
1892       if (strncmp (tokstart, "true", 4) == 0)
1893         return TRUEKEYWORD;
1894       break;
1895     case 3:
1896       HANDLE_SPECIAL ("VTT for ", DEMANGLE_COMPONENT_VTT);
1897       HANDLE_SPECIAL ("non-virtual thunk to ", DEMANGLE_COMPONENT_THUNK);
1898       if (strncmp (tokstart, "new", 3) == 0)
1899         return NEW;
1900       if (strncmp (tokstart, "int", 3) == 0)
1901         return INT_KEYWORD;
1902       break;
1903     default:
1904       break;
1905     }
1906
1907   lvalp->comp = make_name (state, tokstart, namelen);
1908   return NAME;
1909 }
1910
1911 static void
1912 yyerror (cpname_state *state, const char *msg)
1913 {
1914   if (state->global_errmsg)
1915     return;
1916
1917   state->error_lexptr = state->prev_lexptr;
1918   state->global_errmsg = msg ? msg : "parse error";
1919 }
1920
1921 /* Allocate a chunk of the components we'll need to build a tree.  We
1922    generally allocate too many components, but the extra memory usage
1923    doesn't hurt because the trees are temporary and the storage is
1924    reused.  More may be allocated later, by d_grab.  */
1925 static struct demangle_info *
1926 allocate_info (void)
1927 {
1928   struct demangle_info *info = XNEW (struct demangle_info);
1929
1930   info->next = NULL;
1931   info->used = 0;
1932   return info;
1933 }
1934
1935 /* Convert RESULT to a string.  The return value is allocated
1936    using xmalloc.  ESTIMATED_LEN is used only as a guide to the
1937    length of the result.  This functions handles a few cases that
1938    cplus_demangle_print does not, specifically the global destructor
1939    and constructor labels.  */
1940
1941 gdb::unique_xmalloc_ptr<char>
1942 cp_comp_to_string (struct demangle_component *result, int estimated_len)
1943 {
1944   size_t err;
1945
1946   char *res = cplus_demangle_print (DMGL_PARAMS | DMGL_ANSI,
1947                                     result, estimated_len, &err);
1948   return gdb::unique_xmalloc_ptr<char> (res);
1949 }
1950
1951 /* Constructor for demangle_parse_info.  */
1952
1953 demangle_parse_info::demangle_parse_info ()
1954 : info (NULL),
1955   tree (NULL)
1956 {
1957   obstack_init (&obstack);
1958 }
1959
1960 /* Destructor for demangle_parse_info.  */
1961
1962 demangle_parse_info::~demangle_parse_info ()
1963 {
1964   /* Free any allocated chunks of memory for the parse.  */
1965   while (info != NULL)
1966     {
1967       struct demangle_info *next = info->next;
1968
1969       free (info);
1970       info = next;
1971     }
1972
1973   /* Free any memory allocated during typedef replacement.  */
1974   obstack_free (&obstack, NULL);
1975 }
1976
1977 /* Merge the two parse trees given by DEST and SRC.  The parse tree
1978    in SRC is attached to DEST at the node represented by TARGET.
1979
1980    NOTE 1: Since there is no API to merge obstacks, this function does
1981    even attempt to try it.  Fortunately, we do not (yet?) need this ability.
1982    The code will assert if SRC->obstack is not empty.
1983
1984    NOTE 2: The string from which SRC was parsed must not be freed, since
1985    this function will place pointers to that string into DEST.  */
1986
1987 void
1988 cp_merge_demangle_parse_infos (struct demangle_parse_info *dest,
1989                                struct demangle_component *target,
1990                                struct demangle_parse_info *src)
1991
1992 {
1993   struct demangle_info *di;
1994
1995   /* Copy the SRC's parse data into DEST.  */
1996   *target = *src->tree;
1997   di = dest->info;
1998   while (di->next != NULL)
1999     di = di->next;
2000   di->next = src->info;
2001
2002   /* Clear the (pointer to) SRC's parse data so that it is not freed when
2003      cp_demangled_parse_info_free is called.  */
2004   src->info = NULL;
2005 }
2006
2007 /* Convert a demangled name to a demangle_component tree.  On success,
2008    a structure containing the root of the new tree is returned.  On
2009    error, NULL is returned, and an error message will be set in
2010    *ERRMSG.  */
2011
2012 struct std::unique_ptr<demangle_parse_info>
2013 cp_demangled_name_to_comp (const char *demangled_name,
2014                            std::string *errmsg)
2015 {
2016   cpname_state state;
2017
2018   state.prev_lexptr = state.lexptr = demangled_name;
2019   state.error_lexptr = NULL;
2020   state.global_errmsg = NULL;
2021
2022   state.demangle_info = allocate_info ();
2023
2024   std::unique_ptr<demangle_parse_info> result (new demangle_parse_info);
2025   result->info = state.demangle_info;
2026
2027   if (yyparse (&state))
2028     {
2029       if (state.global_errmsg && errmsg)
2030         *errmsg = state.global_errmsg;
2031       return NULL;
2032     }
2033
2034   result->tree = state.global_result;
2035
2036   return result;
2037 }
2038
2039 #ifdef TEST_CPNAMES
2040
2041 static void
2042 cp_print (struct demangle_component *result)
2043 {
2044   char *str;
2045   size_t err = 0;
2046
2047   str = cplus_demangle_print (DMGL_PARAMS | DMGL_ANSI, result, 64, &err);
2048   if (str == NULL)
2049     return;
2050
2051   fputs (str, stdout);
2052
2053   free (str);
2054 }
2055
2056 static char
2057 trim_chars (char *lexptr, char **extra_chars)
2058 {
2059   char *p = (char *) symbol_end (lexptr);
2060   char c = 0;
2061
2062   if (*p)
2063     {
2064       c = *p;
2065       *p = 0;
2066       *extra_chars = p + 1;
2067     }
2068
2069   return c;
2070 }
2071
2072 /* When this file is built as a standalone program, xmalloc comes from
2073    libiberty --- in which case we have to provide xfree ourselves.  */
2074
2075 void
2076 xfree (void *ptr)
2077 {
2078   if (ptr != NULL)
2079     {
2080       /* Literal `free' would get translated back to xfree again.  */
2081       CONCAT2 (fr,ee) (ptr);
2082     }
2083 }
2084
2085 /* GDB normally defines internal_error itself, but when this file is built
2086    as a standalone program, we must also provide an implementation.  */
2087
2088 void
2089 internal_error (const char *file, int line, const char *fmt, ...)
2090 {
2091   va_list ap;
2092
2093   va_start (ap, fmt);
2094   fprintf (stderr, "%s:%d: internal error: ", file, line);
2095   vfprintf (stderr, fmt, ap);
2096   exit (1);
2097 }
2098
2099 int
2100 main (int argc, char **argv)
2101 {
2102   char *str2, *extra_chars, c;
2103   char buf[65536];
2104   int arg;
2105
2106   arg = 1;
2107   if (argv[arg] && strcmp (argv[arg], "--debug") == 0)
2108     {
2109       yydebug = 1;
2110       arg++;
2111     }
2112
2113   if (argv[arg] == NULL)
2114     while (fgets (buf, 65536, stdin) != NULL)
2115       {
2116         int len;
2117         buf[strlen (buf) - 1] = 0;
2118         /* Use DMGL_VERBOSE to get expanded standard substitutions.  */
2119         c = trim_chars (buf, &extra_chars);
2120         str2 = cplus_demangle (buf, DMGL_PARAMS | DMGL_ANSI | DMGL_VERBOSE);
2121         if (str2 == NULL)
2122           {
2123             printf ("Demangling error\n");
2124             if (c)
2125               printf ("%s%c%s\n", buf, c, extra_chars);
2126             else
2127               printf ("%s\n", buf);
2128             continue;
2129           }
2130
2131         std::string errmsg;
2132         std::unique_ptr<demangle_parse_info> result
2133           = cp_demangled_name_to_comp (str2, &errmsg);
2134         if (result == NULL)
2135           {
2136             fputs (errmsg.c_str (), stderr);
2137             fputc ('\n', stderr);
2138             continue;
2139           }
2140
2141         cp_print (result->tree);
2142
2143         free (str2);
2144         if (c)
2145           {
2146             putchar (c);
2147             fputs (extra_chars, stdout);
2148           }
2149         putchar ('\n');
2150       }
2151   else
2152     {
2153       std::string errmsg;
2154       std::unique_ptr<demangle_parse_info> result
2155         = cp_demangled_name_to_comp (argv[arg], &errmsg);
2156       if (result == NULL)
2157         {
2158           fputs (errmsg.c_str (), stderr);
2159           fputc ('\n', stderr);
2160           return 0;
2161         }
2162       cp_print (result->tree);
2163       putchar ('\n');
2164     }
2165   return 0;
2166 }
2167
2168 #endif