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