2002-09-18 Michael Snyder <msnyder@redhat.com>
[external/binutils.git] / gdb / jv-exp.y
1 /* YACC parser for Java expressions, for GDB.
2    Copyright 1997, 1998, 1999, 2000
3    Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
20
21 /* Parse a Java expression from text in a string,
22    and return the result as a  struct expression  pointer.
23    That structure contains arithmetic operations in reverse polish,
24    with constants represented by operations that are followed by special data.
25    See expression.h for the details of the format.
26    What is important here is that it can be built up sequentially
27    during the process of parsing; the lower levels of the tree always
28    come first in the result.  Well, almost always; see ArrayAccess.
29
30    Note that malloc's and realloc's in this file are transformed to
31    xmalloc and xrealloc respectively by the same sed command in the
32    makefile that remaps any other malloc/realloc inserted by the parser
33    generator.  Doing this with #defines and trying to control the interaction
34    with include files (<malloc.h> and <stdlib.h> for example) just became
35    too messy, particularly when such includes can be inserted at random
36    times by the parser generator.  */
37   
38 %{
39
40 #include "defs.h"
41 #include "gdb_string.h"
42 #include <ctype.h>
43 #include "expression.h"
44 #include "value.h"
45 #include "parser-defs.h"
46 #include "language.h"
47 #include "jv-lang.h"
48 #include "bfd.h" /* Required by objfiles.h.  */
49 #include "symfile.h" /* Required by objfiles.h.  */
50 #include "objfiles.h" /* For have_full_symbols and have_partial_symbols */
51 #include "completer.h" /* For skip_quoted().  */
52
53 /* Remap normal yacc parser interface names (yyparse, yylex, yyerror, etc),
54    as well as gratuitiously global symbol names, so we can have multiple
55    yacc generated parsers in gdb.  Note that these are only the variables
56    produced by yacc.  If other parser generators (bison, byacc, etc) produce
57    additional global names that conflict at link time, then those parser
58    generators need to be fixed instead of adding those names to this list. */
59
60 #define yymaxdepth java_maxdepth
61 #define yyparse java_parse
62 #define yylex   java_lex
63 #define yyerror java_error
64 #define yylval  java_lval
65 #define yychar  java_char
66 #define yydebug java_debug
67 #define yypact  java_pact       
68 #define yyr1    java_r1                 
69 #define yyr2    java_r2                 
70 #define yydef   java_def                
71 #define yychk   java_chk                
72 #define yypgo   java_pgo                
73 #define yyact   java_act                
74 #define yyexca  java_exca
75 #define yyerrflag java_errflag
76 #define yynerrs java_nerrs
77 #define yyps    java_ps
78 #define yypv    java_pv
79 #define yys     java_s
80 #define yy_yys  java_yys
81 #define yystate java_state
82 #define yytmp   java_tmp
83 #define yyv     java_v
84 #define yy_yyv  java_yyv
85 #define yyval   java_val
86 #define yylloc  java_lloc
87 #define yyreds  java_reds               /* With YYDEBUG defined */
88 #define yytoks  java_toks               /* With YYDEBUG defined */
89 #define yyname  java_name               /* With YYDEBUG defined */
90 #define yyrule  java_rule               /* With YYDEBUG defined */
91 #define yylhs   java_yylhs
92 #define yylen   java_yylen
93 #define yydefred java_yydefred
94 #define yydgoto java_yydgoto
95 #define yysindex java_yysindex
96 #define yyrindex java_yyrindex
97 #define yygindex java_yygindex
98 #define yytable  java_yytable
99 #define yycheck  java_yycheck
100
101 #ifndef YYDEBUG
102 #define YYDEBUG 1               /* Default to yydebug support */
103 #endif
104
105 #define YYFPRINTF parser_fprintf
106
107 int yyparse (void);
108
109 static int yylex (void);
110
111 void yyerror (char *);
112
113 static struct type *java_type_from_name (struct stoken);
114 static void push_expression_name (struct stoken);
115 static void push_fieldnames (struct stoken);
116
117 static struct expression *copy_exp (struct expression *, int);
118 static void insert_exp (int, struct expression *);
119
120 %}
121
122 /* Although the yacc "value" of an expression is not used,
123    since the result is stored in the structure being created,
124    other node types do have values.  */
125
126 %union
127   {
128     LONGEST lval;
129     struct {
130       LONGEST val;
131       struct type *type;
132     } typed_val_int;
133     struct {
134       DOUBLEST dval;
135       struct type *type;
136     } typed_val_float;
137     struct symbol *sym;
138     struct type *tval;
139     struct stoken sval;
140     struct ttype tsym;
141     struct symtoken ssym;
142     struct block *bval;
143     enum exp_opcode opcode;
144     struct internalvar *ivar;
145     int *ivec;
146   }
147
148 %{
149 /* YYSTYPE gets defined by %union */
150 static int parse_number (char *, int, int, YYSTYPE *);
151 %}
152
153 %type <lval> rcurly Dims Dims_opt
154 %type <tval> ClassOrInterfaceType ClassType /* ReferenceType Type ArrayType */
155 %type <tval> IntegralType FloatingPointType NumericType PrimitiveType ArrayType PrimitiveOrArrayType
156
157 %token <typed_val_int> INTEGER_LITERAL
158 %token <typed_val_float> FLOATING_POINT_LITERAL
159
160 %token <sval> IDENTIFIER
161 %token <sval> STRING_LITERAL
162 %token <lval> BOOLEAN_LITERAL
163 %token <tsym> TYPENAME
164 %type <sval> Name SimpleName QualifiedName ForcedName
165
166 /* A NAME_OR_INT is a symbol which is not known in the symbol table,
167    but which would parse as a valid number in the current input radix.
168    E.g. "c" when input_radix==16.  Depending on the parse, it will be
169    turned into a name or into a number.  */
170
171 %token <sval> NAME_OR_INT 
172
173 %token ERROR
174
175 /* Special type cases, put in to allow the parser to distinguish different
176    legal basetypes.  */
177 %token LONG SHORT BYTE INT CHAR BOOLEAN DOUBLE FLOAT
178
179 %token VARIABLE
180
181 %token <opcode> ASSIGN_MODIFY
182
183 %token THIS SUPER NEW
184
185 %left ','
186 %right '=' ASSIGN_MODIFY
187 %right '?'
188 %left OROR
189 %left ANDAND
190 %left '|'
191 %left '^'
192 %left '&'
193 %left EQUAL NOTEQUAL
194 %left '<' '>' LEQ GEQ
195 %left LSH RSH
196 %left '+' '-'
197 %left '*' '/' '%'
198 %right INCREMENT DECREMENT
199 %right '.' '[' '('
200
201 \f
202 %%
203
204 start   :       exp1
205         |       type_exp
206         ;
207
208 type_exp:       PrimitiveOrArrayType
209                 {
210                   write_exp_elt_opcode(OP_TYPE);
211                   write_exp_elt_type($1);
212                   write_exp_elt_opcode(OP_TYPE);
213                 }
214         ;
215
216 PrimitiveOrArrayType:
217                 PrimitiveType
218         |       ArrayType
219         ;
220
221 StringLiteral:
222         STRING_LITERAL
223                 {
224                   write_exp_elt_opcode (OP_STRING);
225                   write_exp_string ($1);
226                   write_exp_elt_opcode (OP_STRING);
227                 }
228 ;
229
230 Literal:
231         INTEGER_LITERAL
232                 { write_exp_elt_opcode (OP_LONG);
233                   write_exp_elt_type ($1.type);
234                   write_exp_elt_longcst ((LONGEST)($1.val));
235                   write_exp_elt_opcode (OP_LONG); }
236 |       NAME_OR_INT
237                 { YYSTYPE val;
238                   parse_number ($1.ptr, $1.length, 0, &val);
239                   write_exp_elt_opcode (OP_LONG);
240                   write_exp_elt_type (val.typed_val_int.type);
241                   write_exp_elt_longcst ((LONGEST)val.typed_val_int.val);
242                   write_exp_elt_opcode (OP_LONG);
243                 }
244 |       FLOATING_POINT_LITERAL
245                 { write_exp_elt_opcode (OP_DOUBLE);
246                   write_exp_elt_type ($1.type);
247                   write_exp_elt_dblcst ($1.dval);
248                   write_exp_elt_opcode (OP_DOUBLE); }
249 |       BOOLEAN_LITERAL
250                 { write_exp_elt_opcode (OP_LONG);
251                   write_exp_elt_type (java_boolean_type);
252                   write_exp_elt_longcst ((LONGEST)$1);
253                   write_exp_elt_opcode (OP_LONG); }
254 |       StringLiteral
255         ;
256
257 /* UNUSED:
258 Type:
259         PrimitiveType
260 |       ReferenceType
261 ;
262 */
263
264 PrimitiveType:
265         NumericType
266 |       BOOLEAN
267                 { $$ = java_boolean_type; }
268 ;
269
270 NumericType:
271         IntegralType
272 |       FloatingPointType
273 ;
274
275 IntegralType:
276         BYTE
277                 { $$ = java_byte_type; }
278 |       SHORT
279                 { $$ = java_short_type; }
280 |       INT
281                 { $$ = java_int_type; }
282 |       LONG
283                 { $$ = java_long_type; }
284 |       CHAR
285                 { $$ = java_char_type; }
286 ;
287
288 FloatingPointType:
289         FLOAT
290                 { $$ = java_float_type; }
291 |       DOUBLE
292                 { $$ = java_double_type; }
293 ;
294
295 /* UNUSED:
296 ReferenceType:
297         ClassOrInterfaceType
298 |       ArrayType
299 ;
300 */
301
302 ClassOrInterfaceType:
303         Name
304                 { $$ = java_type_from_name ($1); }
305 ;
306
307 ClassType:
308         ClassOrInterfaceType
309 ;
310
311 ArrayType:
312         PrimitiveType Dims
313                 { $$ = java_array_type ($1, $2); }
314 |       Name Dims
315                 { $$ = java_array_type (java_type_from_name ($1), $2); }
316 ;
317
318 Name:
319         IDENTIFIER
320 |       QualifiedName
321 ;
322
323 ForcedName:
324         SimpleName
325 |       QualifiedName
326 ;
327
328 SimpleName:
329         IDENTIFIER
330 |       NAME_OR_INT
331 ;
332
333 QualifiedName:
334         Name '.' SimpleName
335                 { $$.length = $1.length + $3.length + 1;
336                   if ($1.ptr + $1.length + 1 == $3.ptr
337                       && $1.ptr[$1.length] == '.')
338                     $$.ptr = $1.ptr;  /* Optimization. */
339                   else
340                     {
341                       $$.ptr = (char *) malloc ($$.length + 1);
342                       make_cleanup (free, $$.ptr);
343                       sprintf ($$.ptr, "%.*s.%.*s",
344                                $1.length, $1.ptr, $3.length, $3.ptr);
345                 } }
346 ;
347
348 /*
349 type_exp:       type
350                         { write_exp_elt_opcode(OP_TYPE);
351                           write_exp_elt_type($1);
352                           write_exp_elt_opcode(OP_TYPE);}
353         ;
354         */
355
356 /* Expressions, including the comma operator.  */
357 exp1    :       Expression
358         |       exp1 ',' Expression
359                         { write_exp_elt_opcode (BINOP_COMMA); }
360         ;
361
362 Primary:
363         PrimaryNoNewArray
364 |       ArrayCreationExpression
365 ;
366
367 PrimaryNoNewArray:
368         Literal
369 |       THIS
370                 { write_exp_elt_opcode (OP_THIS);
371                   write_exp_elt_opcode (OP_THIS); }
372 |       '(' Expression ')'
373 |       ClassInstanceCreationExpression
374 |       FieldAccess
375 |       MethodInvocation
376 |       ArrayAccess
377 |       lcurly ArgumentList rcurly
378                 { write_exp_elt_opcode (OP_ARRAY);
379                   write_exp_elt_longcst ((LONGEST) 0);
380                   write_exp_elt_longcst ((LONGEST) $3);
381                   write_exp_elt_opcode (OP_ARRAY); }
382 ;
383
384 lcurly:
385         '{'
386                 { start_arglist (); }
387 ;
388
389 rcurly:
390         '}'
391                 { $$ = end_arglist () - 1; }
392 ;
393
394 ClassInstanceCreationExpression:
395         NEW ClassType '(' ArgumentList_opt ')'
396                 { internal_error (__FILE__, __LINE__,
397                                   _("FIXME - ClassInstanceCreationExpression")); }
398 ;
399
400 ArgumentList:
401         Expression
402                 { arglist_len = 1; }
403 |       ArgumentList ',' Expression
404                 { arglist_len++; }
405 ;
406
407 ArgumentList_opt:
408         /* EMPTY */
409                 { arglist_len = 0; }
410 | ArgumentList
411 ;
412
413 ArrayCreationExpression:
414         NEW PrimitiveType DimExprs Dims_opt
415                 { internal_error (__FILE__, __LINE__,
416                                   _("FIXME - ArrayCreationExpression")); }
417 |       NEW ClassOrInterfaceType DimExprs Dims_opt
418                 { internal_error (__FILE__, __LINE__,
419                                   _("FIXME - ArrayCreationExpression")); }
420 ;
421
422 DimExprs:
423         DimExpr
424 |       DimExprs DimExpr
425 ;
426
427 DimExpr:
428         '[' Expression ']'
429 ;
430
431 Dims:
432         '[' ']'
433                 { $$ = 1; }
434 |       Dims '[' ']'
435         { $$ = $1 + 1; }
436 ;
437
438 Dims_opt:
439         Dims
440 |       /* EMPTY */
441                 { $$ = 0; }
442 ;
443
444 FieldAccess:
445         Primary '.' SimpleName
446                 { push_fieldnames ($3); }
447 |       VARIABLE '.' SimpleName
448                 { push_fieldnames ($3); }
449 /*|     SUPER '.' SimpleName { FIXME } */
450 ;
451
452 MethodInvocation:
453         Name '(' ArgumentList_opt ')'
454                 { error (_("Method invocation not implemented")); }
455 |       Primary '.' SimpleName '(' ArgumentList_opt ')'
456                 { error (_("Method invocation not implemented")); }
457 |       SUPER '.' SimpleName '(' ArgumentList_opt ')'
458                 { error (_("Method invocation not implemented")); }
459 ;
460
461 ArrayAccess:
462         Name '[' Expression ']'
463                 {
464                   /* Emit code for the Name now, then exchange it in the
465                      expout array with the Expression's code.  We could
466                      introduce a OP_SWAP code or a reversed version of
467                      BINOP_SUBSCRIPT, but that makes the rest of GDB pay
468                      for our parsing kludges.  */
469                   struct expression *name_expr;
470
471                   push_expression_name ($1);
472                   name_expr = copy_exp (expout, expout_ptr);
473                   expout_ptr -= name_expr->nelts;
474                   insert_exp (expout_ptr-length_of_subexp (expout, expout_ptr),
475                               name_expr);
476                   free (name_expr);
477                   write_exp_elt_opcode (BINOP_SUBSCRIPT);
478                 }
479 |       VARIABLE '[' Expression ']'
480                 { write_exp_elt_opcode (BINOP_SUBSCRIPT); }
481 |       PrimaryNoNewArray '[' Expression ']'
482                 { write_exp_elt_opcode (BINOP_SUBSCRIPT); }
483 ;
484
485 PostfixExpression:
486         Primary
487 |       Name
488                 { push_expression_name ($1); }
489 |       VARIABLE
490                 /* Already written by write_dollar_variable. */
491 |       PostIncrementExpression
492 |       PostDecrementExpression
493 ;
494
495 PostIncrementExpression:
496         PostfixExpression INCREMENT
497                 { write_exp_elt_opcode (UNOP_POSTINCREMENT); }
498 ;
499
500 PostDecrementExpression:
501         PostfixExpression DECREMENT
502                 { write_exp_elt_opcode (UNOP_POSTDECREMENT); }
503 ;
504
505 UnaryExpression:
506         PreIncrementExpression
507 |       PreDecrementExpression
508 |       '+' UnaryExpression
509 |       '-' UnaryExpression
510                 { write_exp_elt_opcode (UNOP_NEG); }
511 |       '*' UnaryExpression 
512                 { write_exp_elt_opcode (UNOP_IND); } /*FIXME not in Java  */
513 |       UnaryExpressionNotPlusMinus
514 ;
515
516 PreIncrementExpression:
517         INCREMENT UnaryExpression
518                 { write_exp_elt_opcode (UNOP_PREINCREMENT); }
519 ;
520
521 PreDecrementExpression:
522         DECREMENT UnaryExpression
523                 { write_exp_elt_opcode (UNOP_PREDECREMENT); }
524 ;
525
526 UnaryExpressionNotPlusMinus:
527         PostfixExpression
528 |       '~' UnaryExpression
529                 { write_exp_elt_opcode (UNOP_COMPLEMENT); }
530 |       '!' UnaryExpression
531                 { write_exp_elt_opcode (UNOP_LOGICAL_NOT); }
532 |       CastExpression
533         ;
534
535 CastExpression:
536         '(' PrimitiveType Dims_opt ')' UnaryExpression
537                 { write_exp_elt_opcode (UNOP_CAST);
538                   write_exp_elt_type (java_array_type ($2, $3));
539                   write_exp_elt_opcode (UNOP_CAST); }
540 |       '(' Expression ')' UnaryExpressionNotPlusMinus
541                 {
542                   int exp_size = expout_ptr;
543                   int last_exp_size = length_of_subexp(expout, expout_ptr);
544                   struct type *type;
545                   int i;
546                   int base = expout_ptr - last_exp_size - 3;
547                   if (base < 0 || expout->elts[base+2].opcode != OP_TYPE)
548                     error (_("Invalid cast expression"));
549                   type = expout->elts[base+1].type;
550                   /* Remove the 'Expression' and slide the
551                      UnaryExpressionNotPlusMinus down to replace it. */
552                   for (i = 0;  i < last_exp_size;  i++)
553                     expout->elts[base + i] = expout->elts[base + i + 3];
554                   expout_ptr -= 3;
555                   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
556                     type = lookup_pointer_type (type);
557                   write_exp_elt_opcode (UNOP_CAST);
558                   write_exp_elt_type (type);
559                   write_exp_elt_opcode (UNOP_CAST);
560                 }
561 |       '(' Name Dims ')' UnaryExpressionNotPlusMinus
562                 { write_exp_elt_opcode (UNOP_CAST);
563                   write_exp_elt_type (java_array_type (java_type_from_name ($2), $3));
564                   write_exp_elt_opcode (UNOP_CAST); }
565 ;
566
567
568 MultiplicativeExpression:
569         UnaryExpression
570 |       MultiplicativeExpression '*' UnaryExpression
571                 { write_exp_elt_opcode (BINOP_MUL); }
572 |       MultiplicativeExpression '/' UnaryExpression
573                 { write_exp_elt_opcode (BINOP_DIV); }
574 |       MultiplicativeExpression '%' UnaryExpression
575                 { write_exp_elt_opcode (BINOP_REM); }
576 ;
577
578 AdditiveExpression:
579         MultiplicativeExpression
580 |       AdditiveExpression '+' MultiplicativeExpression
581                 { write_exp_elt_opcode (BINOP_ADD); }
582 |       AdditiveExpression '-' MultiplicativeExpression
583                 { write_exp_elt_opcode (BINOP_SUB); }
584 ;
585
586 ShiftExpression:
587         AdditiveExpression
588 |       ShiftExpression LSH AdditiveExpression
589                 { write_exp_elt_opcode (BINOP_LSH); }
590 |       ShiftExpression RSH AdditiveExpression
591                 { write_exp_elt_opcode (BINOP_RSH); }
592 /* |    ShiftExpression >>> AdditiveExpression { FIXME } */
593 ;
594
595 RelationalExpression:
596         ShiftExpression
597 |       RelationalExpression '<' ShiftExpression
598                 { write_exp_elt_opcode (BINOP_LESS); }
599 |       RelationalExpression '>' ShiftExpression
600                 { write_exp_elt_opcode (BINOP_GTR); }
601 |       RelationalExpression LEQ ShiftExpression
602                 { write_exp_elt_opcode (BINOP_LEQ); }
603 |       RelationalExpression GEQ ShiftExpression
604                 { write_exp_elt_opcode (BINOP_GEQ); }
605 /* | RelationalExpresion INSTANCEOF ReferenceType { FIXME } */
606 ;
607
608 EqualityExpression:
609         RelationalExpression
610 |       EqualityExpression EQUAL RelationalExpression
611                 { write_exp_elt_opcode (BINOP_EQUAL); }
612 |       EqualityExpression NOTEQUAL RelationalExpression
613                 { write_exp_elt_opcode (BINOP_NOTEQUAL); }
614 ;
615
616 AndExpression:
617         EqualityExpression
618 |       AndExpression '&' EqualityExpression
619                 { write_exp_elt_opcode (BINOP_BITWISE_AND); }
620 ;
621
622 ExclusiveOrExpression:
623         AndExpression
624 |       ExclusiveOrExpression '^' AndExpression
625                 { write_exp_elt_opcode (BINOP_BITWISE_XOR); }
626 ;
627 InclusiveOrExpression:
628         ExclusiveOrExpression
629 |       InclusiveOrExpression '|' ExclusiveOrExpression
630                 { write_exp_elt_opcode (BINOP_BITWISE_IOR); }
631 ;
632
633 ConditionalAndExpression:
634         InclusiveOrExpression
635 |       ConditionalAndExpression ANDAND InclusiveOrExpression
636                 { write_exp_elt_opcode (BINOP_LOGICAL_AND); }
637 ;
638
639 ConditionalOrExpression:
640         ConditionalAndExpression
641 |       ConditionalOrExpression OROR ConditionalAndExpression
642                 { write_exp_elt_opcode (BINOP_LOGICAL_OR); }
643 ;
644
645 ConditionalExpression:
646         ConditionalOrExpression
647 |       ConditionalOrExpression '?' Expression ':' ConditionalExpression
648                 { write_exp_elt_opcode (TERNOP_COND); }
649 ;
650
651 AssignmentExpression:
652         ConditionalExpression
653 |       Assignment
654 ;
655                           
656 Assignment:
657         LeftHandSide '=' ConditionalExpression
658                 { write_exp_elt_opcode (BINOP_ASSIGN); }
659 |       LeftHandSide ASSIGN_MODIFY ConditionalExpression
660                 { write_exp_elt_opcode (BINOP_ASSIGN_MODIFY);
661                   write_exp_elt_opcode ($2);
662                   write_exp_elt_opcode (BINOP_ASSIGN_MODIFY); }
663 ;
664
665 LeftHandSide:
666         ForcedName
667                 { push_expression_name ($1); }
668 |       VARIABLE
669                 /* Already written by write_dollar_variable. */
670 |       FieldAccess
671 |       ArrayAccess
672 ;
673
674
675 Expression:
676         AssignmentExpression
677 ;
678
679 %%
680 /* Take care of parsing a number (anything that starts with a digit).
681    Set yylval and return the token type; update lexptr.
682    LEN is the number of characters in it.  */
683
684 /*** Needs some error checking for the float case ***/
685
686 static int
687 parse_number (p, len, parsed_float, putithere)
688      register char *p;
689      register int len;
690      int parsed_float;
691      YYSTYPE *putithere;
692 {
693   register ULONGEST n = 0;
694   ULONGEST limit, limit_div_base;
695
696   register int c;
697   register int base = input_radix;
698
699   struct type *type;
700
701   if (parsed_float)
702     {
703       /* It's a float since it contains a point or an exponent.  */
704       char c;
705       int num = 0;      /* number of tokens scanned by scanf */
706       char saved_char = p[len];
707
708       p[len] = 0;       /* null-terminate the token */
709       if (sizeof (putithere->typed_val_float.dval) <= sizeof (float))
710         num = sscanf (p, "%g%c", (float *) &putithere->typed_val_float.dval, &c);
711       else if (sizeof (putithere->typed_val_float.dval) <= sizeof (double))
712         num = sscanf (p, "%lg%c", (double *) &putithere->typed_val_float.dval, &c);
713       else
714         {
715 #ifdef SCANF_HAS_LONG_DOUBLE
716           num = sscanf (p, "%Lg%c", &putithere->typed_val_float.dval, &c);
717 #else
718           /* Scan it into a double, then assign it to the long double.
719              This at least wins with values representable in the range
720              of doubles. */
721           double temp;
722           num = sscanf (p, "%lg%c", &temp, &c);
723           putithere->typed_val_float.dval = temp;
724 #endif
725         }
726       p[len] = saved_char;      /* restore the input stream */
727       if (num != 1)             /* check scanf found ONLY a float ... */
728         return ERROR;
729       /* See if it has `f' or `d' suffix (float or double).  */
730
731       c = tolower (p[len - 1]);
732
733       if (c == 'f' || c == 'F')
734         putithere->typed_val_float.type = builtin_type_float;
735       else if (isdigit (c) || c == '.' || c == 'd' || c == 'D')
736         putithere->typed_val_float.type = builtin_type_double;
737       else
738         return ERROR;
739
740       return FLOATING_POINT_LITERAL;
741     }
742
743   /* Handle base-switching prefixes 0x, 0t, 0d, 0 */
744   if (p[0] == '0')
745     switch (p[1])
746       {
747       case 'x':
748       case 'X':
749         if (len >= 3)
750           {
751             p += 2;
752             base = 16;
753             len -= 2;
754           }
755         break;
756
757       case 't':
758       case 'T':
759       case 'd':
760       case 'D':
761         if (len >= 3)
762           {
763             p += 2;
764             base = 10;
765             len -= 2;
766           }
767         break;
768
769       default:
770         base = 8;
771         break;
772       }
773
774   c = p[len-1];
775   /* A paranoid calculation of (1<<64)-1. */
776   limit = (ULONGEST)0xffffffff;
777   limit = ((limit << 16) << 16) | limit;
778   if (c == 'l' || c == 'L')
779     {
780       type = java_long_type;
781       len--;
782     }
783   else
784     {
785       type = java_int_type;
786     }
787   limit_div_base = limit / (ULONGEST) base;
788
789   while (--len >= 0)
790     {
791       c = *p++;
792       if (c >= '0' && c <= '9')
793         c -= '0';
794       else if (c >= 'A' && c <= 'Z')
795         c -= 'A' - 10;
796       else if (c >= 'a' && c <= 'z')
797         c -= 'a' - 10;
798       else
799         return ERROR;   /* Char not a digit */
800       if (c >= base)
801         return ERROR;
802       if (n > limit_div_base
803           || (n *= base) > limit - c)
804         error (_("Numeric constant too large"));
805       n += c;
806         }
807
808   /* If the type is bigger than a 32-bit signed integer can be, implicitly
809      promote to long.  Java does not do this, so mark it as builtin_type_uint64
810      rather than java_long_type.  0x80000000 will become -0x80000000 instead
811      of 0x80000000L, because we don't know the sign at this point.
812   */
813   if (type == java_int_type && n > (ULONGEST)0x80000000)
814     type = builtin_type_uint64;
815
816   putithere->typed_val_int.val = n;
817   putithere->typed_val_int.type = type;
818
819   return INTEGER_LITERAL;
820 }
821
822 struct token
823 {
824   char *operator;
825   int token;
826   enum exp_opcode opcode;
827 };
828
829 static const struct token tokentab3[] =
830   {
831     {">>=", ASSIGN_MODIFY, BINOP_RSH},
832     {"<<=", ASSIGN_MODIFY, BINOP_LSH}
833   };
834
835 static const struct token tokentab2[] =
836   {
837     {"+=", ASSIGN_MODIFY, BINOP_ADD},
838     {"-=", ASSIGN_MODIFY, BINOP_SUB},
839     {"*=", ASSIGN_MODIFY, BINOP_MUL},
840     {"/=", ASSIGN_MODIFY, BINOP_DIV},
841     {"%=", ASSIGN_MODIFY, BINOP_REM},
842     {"|=", ASSIGN_MODIFY, BINOP_BITWISE_IOR},
843     {"&=", ASSIGN_MODIFY, BINOP_BITWISE_AND},
844     {"^=", ASSIGN_MODIFY, BINOP_BITWISE_XOR},
845     {"++", INCREMENT, BINOP_END},
846     {"--", DECREMENT, BINOP_END},
847     {"&&", ANDAND, BINOP_END},
848     {"||", OROR, BINOP_END},
849     {"<<", LSH, BINOP_END},
850     {">>", RSH, BINOP_END},
851     {"==", EQUAL, BINOP_END},
852     {"!=", NOTEQUAL, BINOP_END},
853     {"<=", LEQ, BINOP_END},
854     {">=", GEQ, BINOP_END}
855   };
856
857 /* Read one token, getting characters through lexptr.  */
858
859 static int
860 yylex ()
861 {
862   int c;
863   int namelen;
864   unsigned int i;
865   char *tokstart;
866   char *tokptr;
867   int tempbufindex;
868   static char *tempbuf;
869   static int tempbufsize;
870   
871  retry:
872
873   prev_lexptr = lexptr;
874
875   tokstart = lexptr;
876   /* See if it is a special token of length 3.  */
877   for (i = 0; i < sizeof tokentab3 / sizeof tokentab3[0]; i++)
878     if (STREQN (tokstart, tokentab3[i].operator, 3))
879       {
880         lexptr += 3;
881         yylval.opcode = tokentab3[i].opcode;
882         return tokentab3[i].token;
883       }
884
885   /* See if it is a special token of length 2.  */
886   for (i = 0; i < sizeof tokentab2 / sizeof tokentab2[0]; i++)
887     if (STREQN (tokstart, tokentab2[i].operator, 2))
888       {
889         lexptr += 2;
890         yylval.opcode = tokentab2[i].opcode;
891         return tokentab2[i].token;
892       }
893
894   switch (c = *tokstart)
895     {
896     case 0:
897       return 0;
898
899     case ' ':
900     case '\t':
901     case '\n':
902       lexptr++;
903       goto retry;
904
905     case '\'':
906       /* We either have a character constant ('0' or '\177' for example)
907          or we have a quoted symbol reference ('foo(int,int)' in C++
908          for example). */
909       lexptr++;
910       c = *lexptr++;
911       if (c == '\\')
912         c = parse_escape (&lexptr);
913       else if (c == '\'')
914         error (_("Empty character constant"));
915
916       yylval.typed_val_int.val = c;
917       yylval.typed_val_int.type = java_char_type;
918
919       c = *lexptr++;
920       if (c != '\'')
921         {
922           namelen = skip_quoted (tokstart) - tokstart;
923           if (namelen > 2)
924             {
925               lexptr = tokstart + namelen;
926               if (lexptr[-1] != '\'')
927                 error (_("Unmatched single quote"));
928               namelen -= 2;
929               tokstart++;
930               goto tryname;
931             }
932           error (_("Invalid character constant"));
933         }
934       return INTEGER_LITERAL;
935
936     case '(':
937       paren_depth++;
938       lexptr++;
939       return c;
940
941     case ')':
942       if (paren_depth == 0)
943         return 0;
944       paren_depth--;
945       lexptr++;
946       return c;
947
948     case ',':
949       if (comma_terminates && paren_depth == 0)
950         return 0;
951       lexptr++;
952       return c;
953
954     case '.':
955       /* Might be a floating point number.  */
956       if (lexptr[1] < '0' || lexptr[1] > '9')
957         goto symbol;            /* Nope, must be a symbol. */
958       /* FALL THRU into number case.  */
959
960     case '0':
961     case '1':
962     case '2':
963     case '3':
964     case '4':
965     case '5':
966     case '6':
967     case '7':
968     case '8':
969     case '9':
970       {
971         /* It's a number.  */
972         int got_dot = 0, got_e = 0, toktype;
973         register char *p = tokstart;
974         int hex = input_radix > 10;
975
976         if (c == '0' && (p[1] == 'x' || p[1] == 'X'))
977           {
978             p += 2;
979             hex = 1;
980           }
981         else if (c == '0' && (p[1]=='t' || p[1]=='T' || p[1]=='d' || p[1]=='D'))
982           {
983             p += 2;
984             hex = 0;
985           }
986
987         for (;; ++p)
988           {
989             /* This test includes !hex because 'e' is a valid hex digit
990                and thus does not indicate a floating point number when
991                the radix is hex.  */
992             if (!hex && !got_e && (*p == 'e' || *p == 'E'))
993               got_dot = got_e = 1;
994             /* This test does not include !hex, because a '.' always indicates
995                a decimal floating point number regardless of the radix.  */
996             else if (!got_dot && *p == '.')
997               got_dot = 1;
998             else if (got_e && (p[-1] == 'e' || p[-1] == 'E')
999                      && (*p == '-' || *p == '+'))
1000               /* This is the sign of the exponent, not the end of the
1001                  number.  */
1002               continue;
1003             /* We will take any letters or digits.  parse_number will
1004                complain if past the radix, or if L or U are not final.  */
1005             else if ((*p < '0' || *p > '9')
1006                      && ((*p < 'a' || *p > 'z')
1007                                   && (*p < 'A' || *p > 'Z')))
1008               break;
1009           }
1010         toktype = parse_number (tokstart, p - tokstart, got_dot|got_e, &yylval);
1011         if (toktype == ERROR)
1012           {
1013             char *err_copy = (char *) alloca (p - tokstart + 1);
1014
1015             memcpy (err_copy, tokstart, p - tokstart);
1016             err_copy[p - tokstart] = 0;
1017             error (_("Invalid number \"%s\""), err_copy);
1018           }
1019         lexptr = p;
1020         return toktype;
1021       }
1022
1023     case '+':
1024     case '-':
1025     case '*':
1026     case '/':
1027     case '%':
1028     case '|':
1029     case '&':
1030     case '^':
1031     case '~':
1032     case '!':
1033     case '<':
1034     case '>':
1035     case '[':
1036     case ']':
1037     case '?':
1038     case ':':
1039     case '=':
1040     case '{':
1041     case '}':
1042     symbol:
1043       lexptr++;
1044       return c;
1045
1046     case '"':
1047
1048       /* Build the gdb internal form of the input string in tempbuf,
1049          translating any standard C escape forms seen.  Note that the
1050          buffer is null byte terminated *only* for the convenience of
1051          debugging gdb itself and printing the buffer contents when
1052          the buffer contains no embedded nulls.  Gdb does not depend
1053          upon the buffer being null byte terminated, it uses the length
1054          string instead.  This allows gdb to handle C strings (as well
1055          as strings in other languages) with embedded null bytes */
1056
1057       tokptr = ++tokstart;
1058       tempbufindex = 0;
1059
1060       do {
1061         /* Grow the static temp buffer if necessary, including allocating
1062            the first one on demand. */
1063         if (tempbufindex + 1 >= tempbufsize)
1064           {
1065             tempbuf = (char *) realloc (tempbuf, tempbufsize += 64);
1066           }
1067         switch (*tokptr)
1068           {
1069           case '\0':
1070           case '"':
1071             /* Do nothing, loop will terminate. */
1072             break;
1073           case '\\':
1074             tokptr++;
1075             c = parse_escape (&tokptr);
1076             if (c == -1)
1077               {
1078                 continue;
1079               }
1080             tempbuf[tempbufindex++] = c;
1081             break;
1082           default:
1083             tempbuf[tempbufindex++] = *tokptr++;
1084             break;
1085           }
1086       } while ((*tokptr != '"') && (*tokptr != '\0'));
1087       if (*tokptr++ != '"')
1088         {
1089           error (_("Unterminated string in expression"));
1090         }
1091       tempbuf[tempbufindex] = '\0';     /* See note above */
1092       yylval.sval.ptr = tempbuf;
1093       yylval.sval.length = tempbufindex;
1094       lexptr = tokptr;
1095       return (STRING_LITERAL);
1096     }
1097
1098   if (!(c == '_' || c == '$'
1099         || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')))
1100     /* We must have come across a bad character (e.g. ';').  */
1101     error (_("Invalid character '%c' in expression"), c);
1102
1103   /* It's a name.  See how long it is.  */
1104   namelen = 0;
1105   for (c = tokstart[namelen];
1106        (c == '_'
1107         || c == '$'
1108         || (c >= '0' && c <= '9')
1109         || (c >= 'a' && c <= 'z')
1110         || (c >= 'A' && c <= 'Z')
1111         || c == '<');
1112        )
1113     {
1114       if (c == '<')
1115         {
1116           int i = namelen;
1117           while (tokstart[++i] && tokstart[i] != '>');
1118           if (tokstart[i] == '>')
1119             namelen = i;
1120         }
1121        c = tokstart[++namelen];
1122      }
1123
1124   /* The token "if" terminates the expression and is NOT 
1125      removed from the input stream.  */
1126   if (namelen == 2 && tokstart[0] == 'i' && tokstart[1] == 'f')
1127     {
1128       return 0;
1129     }
1130
1131   lexptr += namelen;
1132
1133   tryname:
1134
1135   /* Catch specific keywords.  Should be done with a data structure.  */
1136   switch (namelen)
1137     {
1138     case 7:
1139       if (STREQN (tokstart, "boolean", 7))
1140         return BOOLEAN;
1141       break;
1142     case 6:
1143       if (STREQN (tokstart, "double", 6))      
1144         return DOUBLE;
1145       break;
1146     case 5:
1147       if (STREQN (tokstart, "short", 5))
1148         return SHORT;
1149       if (STREQN (tokstart, "false", 5))
1150         {
1151           yylval.lval = 0;
1152           return BOOLEAN_LITERAL;
1153         }
1154       if (STREQN (tokstart, "super", 5))
1155         return SUPER;
1156       if (STREQN (tokstart, "float", 5))
1157         return FLOAT;
1158       break;
1159     case 4:
1160       if (STREQN (tokstart, "long", 4))
1161         return LONG;
1162       if (STREQN (tokstart, "byte", 4))
1163         return BYTE;
1164       if (STREQN (tokstart, "char", 4))
1165         return CHAR;
1166       if (STREQN (tokstart, "true", 4))
1167         {
1168           yylval.lval = 1;
1169           return BOOLEAN_LITERAL;
1170         }
1171       if (current_language->la_language == language_cplus
1172           && STREQN (tokstart, "this", 4))
1173         {
1174           static const char this_name[] =
1175                                  { CPLUS_MARKER, 't', 'h', 'i', 's', '\0' };
1176
1177           if (lookup_symbol (this_name, expression_context_block,
1178                              VAR_NAMESPACE, (int *) NULL,
1179                              (struct symtab **) NULL))
1180             return THIS;
1181         }
1182       break;
1183     case 3:
1184       if (STREQN (tokstart, "int", 3))
1185         return INT;
1186       if (STREQN (tokstart, "new", 3))
1187         return NEW;
1188       break;
1189     default:
1190       break;
1191     }
1192
1193   yylval.sval.ptr = tokstart;
1194   yylval.sval.length = namelen;
1195
1196   if (*tokstart == '$')
1197     {
1198       write_dollar_variable (yylval.sval);
1199       return VARIABLE;
1200     }
1201
1202   /* Input names that aren't symbols but ARE valid hex numbers,
1203      when the input radix permits them, can be names or numbers
1204      depending on the parse.  Note we support radixes > 16 here.  */
1205   if (((tokstart[0] >= 'a' && tokstart[0] < 'a' + input_radix - 10) ||
1206        (tokstart[0] >= 'A' && tokstart[0] < 'A' + input_radix - 10)))
1207     {
1208       YYSTYPE newlval;  /* Its value is ignored.  */
1209       int hextype = parse_number (tokstart, namelen, 0, &newlval);
1210       if (hextype == INTEGER_LITERAL)
1211         return NAME_OR_INT;
1212     }
1213   return IDENTIFIER;
1214 }
1215
1216 void
1217 yyerror (msg)
1218      char *msg;
1219 {
1220   if (prev_lexptr)
1221     lexptr = prev_lexptr;
1222
1223   if (msg)
1224     error (_("%s: near `%s'"), msg, lexptr);
1225   else
1226     error (_("error in expression, near `%s'"), lexptr);
1227 }
1228
1229 static struct type *
1230 java_type_from_name (name)
1231      struct stoken name;
1232  
1233 {
1234   char *tmp = copy_name (name);
1235   struct type *typ = java_lookup_class (tmp);
1236   if (typ == NULL || TYPE_CODE (typ) != TYPE_CODE_STRUCT)
1237     error (_("No class named `%s'"), tmp);
1238   return typ;
1239 }
1240
1241 /* If NAME is a valid variable name in this scope, push it and return 1.
1242    Otherwise, return 0. */
1243
1244 static int
1245 push_variable (name)
1246      struct stoken name;
1247  
1248 {
1249   char *tmp = copy_name (name);
1250   int is_a_field_of_this = 0;
1251   struct symbol *sym;
1252   sym = lookup_symbol (tmp, expression_context_block, VAR_NAMESPACE,
1253                        &is_a_field_of_this, (struct symtab **) NULL);
1254   if (sym && SYMBOL_CLASS (sym) != LOC_TYPEDEF)
1255     {
1256       if (symbol_read_needs_frame (sym))
1257         {
1258           if (innermost_block == 0 ||
1259               contained_in (block_found, innermost_block))
1260             innermost_block = block_found;
1261         }
1262
1263       write_exp_elt_opcode (OP_VAR_VALUE);
1264       /* We want to use the selected frame, not another more inner frame
1265          which happens to be in the same block.  */
1266       write_exp_elt_block (NULL);
1267       write_exp_elt_sym (sym);
1268       write_exp_elt_opcode (OP_VAR_VALUE);
1269       return 1;
1270     }
1271   if (is_a_field_of_this)
1272     {
1273       /* it hangs off of `this'.  Must not inadvertently convert from a
1274          method call to data ref.  */
1275       if (innermost_block == 0 || 
1276           contained_in (block_found, innermost_block))
1277         innermost_block = block_found;
1278       write_exp_elt_opcode (OP_THIS);
1279       write_exp_elt_opcode (OP_THIS);
1280       write_exp_elt_opcode (STRUCTOP_PTR);
1281       write_exp_string (name);
1282       write_exp_elt_opcode (STRUCTOP_PTR);
1283       return 1;
1284     }
1285   return 0;
1286 }
1287
1288 /* Assuming a reference expression has been pushed, emit the
1289    STRUCTOP_STRUCT ops to access the field named NAME.  If NAME is a
1290    qualified name (has '.'), generate a field access for each part. */
1291
1292 static void
1293 push_fieldnames (name)
1294      struct stoken name;
1295 {
1296   int i;
1297   struct stoken token;
1298   token.ptr = name.ptr;
1299   for (i = 0;  ;  i++)
1300     {
1301       if (i == name.length || name.ptr[i] == '.')
1302         {
1303           /* token.ptr is start of current field name. */
1304           token.length = &name.ptr[i] - token.ptr;
1305           write_exp_elt_opcode (STRUCTOP_STRUCT);
1306           write_exp_string (token);
1307           write_exp_elt_opcode (STRUCTOP_STRUCT);
1308           token.ptr += token.length + 1;
1309         }
1310       if (i >= name.length)
1311         break;
1312     }
1313 }
1314
1315 /* Helper routine for push_expression_name.
1316    Handle a qualified name, where DOT_INDEX is the index of the first '.' */
1317
1318 static void
1319 push_qualified_expression_name (name, dot_index)
1320      struct stoken name;
1321      int dot_index;
1322 {
1323   struct stoken token;
1324   char *tmp;
1325   struct type *typ;
1326
1327   token.ptr = name.ptr;
1328   token.length = dot_index;
1329
1330   if (push_variable (token))
1331     {
1332       token.ptr = name.ptr + dot_index + 1;
1333       token.length = name.length - dot_index - 1;
1334       push_fieldnames (token);
1335       return;
1336     }
1337
1338   token.ptr = name.ptr;
1339   for (;;)
1340     {
1341       token.length = dot_index;
1342       tmp = copy_name (token);
1343       typ = java_lookup_class (tmp);
1344       if (typ != NULL)
1345         {
1346           if (dot_index == name.length)
1347             {
1348               write_exp_elt_opcode(OP_TYPE);
1349               write_exp_elt_type(typ);
1350               write_exp_elt_opcode(OP_TYPE);
1351               return;
1352             }
1353           dot_index++;  /* Skip '.' */
1354           name.ptr += dot_index;
1355           name.length -= dot_index;
1356           dot_index = 0;
1357           while (dot_index < name.length && name.ptr[dot_index] != '.') 
1358             dot_index++;
1359           token.ptr = name.ptr;
1360           token.length = dot_index;
1361           write_exp_elt_opcode (OP_SCOPE);
1362           write_exp_elt_type (typ);
1363           write_exp_string (token);
1364           write_exp_elt_opcode (OP_SCOPE); 
1365           if (dot_index < name.length)
1366             {
1367               dot_index++;
1368               name.ptr += dot_index;
1369               name.length -= dot_index;
1370               push_fieldnames (name);
1371             }
1372           return;
1373         }
1374       else if (dot_index >= name.length)
1375         break;
1376       dot_index++;  /* Skip '.' */
1377       while (dot_index < name.length && name.ptr[dot_index] != '.')
1378         dot_index++;
1379     }
1380   error (_("unknown type `%.*s'"), name.length, name.ptr);
1381 }
1382
1383 /* Handle Name in an expression (or LHS).
1384    Handle VAR, TYPE, TYPE.FIELD1....FIELDN and VAR.FIELD1....FIELDN. */
1385
1386 static void
1387 push_expression_name (name)
1388      struct stoken name;
1389 {
1390   char *tmp;
1391   struct type *typ;
1392   char *ptr;
1393   int i;
1394
1395   for (i = 0;  i < name.length;  i++)
1396     {
1397       if (name.ptr[i] == '.')
1398         {
1399           /* It's a Qualified Expression Name. */
1400           push_qualified_expression_name (name, i);
1401           return;
1402         }
1403     }
1404
1405   /* It's a Simple Expression Name. */
1406   
1407   if (push_variable (name))
1408     return;
1409   tmp = copy_name (name);
1410   typ = java_lookup_class (tmp);
1411   if (typ != NULL)
1412     {
1413       write_exp_elt_opcode(OP_TYPE);
1414       write_exp_elt_type(typ);
1415       write_exp_elt_opcode(OP_TYPE);
1416     }
1417   else
1418     {
1419       struct minimal_symbol *msymbol;
1420
1421       msymbol = lookup_minimal_symbol (tmp, NULL, NULL);
1422       if (msymbol != NULL)
1423         {
1424           write_exp_msymbol (msymbol,
1425                              lookup_function_type (builtin_type_int),
1426                              builtin_type_int);
1427         }
1428       else if (!have_full_symbols () && !have_partial_symbols ())
1429         error (_("No symbol table is loaded.  Use the \"file\" command"));
1430       else
1431         error (_("No symbol \"%s\" in current context"), tmp);
1432     }
1433
1434 }
1435
1436
1437 /* The following two routines, copy_exp and insert_exp, aren't specific to
1438    Java, so they could go in parse.c, but their only purpose is to support
1439    the parsing kludges we use in this file, so maybe it's best to isolate
1440    them here.  */
1441
1442 /* Copy the expression whose last element is at index ENDPOS - 1 in EXPR
1443    into a freshly malloc'ed struct expression.  Its language_defn is set
1444    to null.  */
1445 static struct expression *
1446 copy_exp (expr, endpos)
1447      struct expression *expr;
1448      int endpos;
1449 {
1450   int len = length_of_subexp (expr, endpos);
1451   struct expression *new
1452     = (struct expression *) malloc (sizeof (*new) + EXP_ELEM_TO_BYTES (len));
1453   new->nelts = len;
1454   memcpy (new->elts, expr->elts + endpos - len, EXP_ELEM_TO_BYTES (len));
1455   new->language_defn = 0;
1456
1457   return new;
1458 }
1459
1460 /* Insert the expression NEW into the current expression (expout) at POS.  */
1461 static void
1462 insert_exp (pos, new)
1463      int pos;
1464      struct expression *new;
1465 {
1466   int newlen = new->nelts;
1467
1468   /* Grow expout if necessary.  In this function's only use at present,
1469      this should never be necessary.  */
1470   if (expout_ptr + newlen > expout_size)
1471     {
1472       expout_size = max (expout_size * 2, expout_ptr + newlen + 10);
1473       expout = (struct expression *)
1474         realloc ((char *) expout, (sizeof (struct expression)
1475                                     + EXP_ELEM_TO_BYTES (expout_size)));
1476     }
1477
1478   {
1479     int i;
1480
1481     for (i = expout_ptr - 1; i >= pos; i--)
1482       expout->elts[i + newlen] = expout->elts[i];
1483   }
1484   
1485   memcpy (expout->elts + pos, new->elts, EXP_ELEM_TO_BYTES (newlen));
1486   expout_ptr += newlen;
1487 }