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