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