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