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