* ada-valprint.c, parse.c: Include defs.h before including ctype.h.
[external/binutils.git] / gdb / parse.c
1 /* Parse expressions for GDB.
2
3    Copyright (C) 1986, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
4    1998, 1999, 2000, 2001, 2004, 2005, 2007, 2008, 2009, 2010
5    Free Software Foundation, Inc.
6
7    Modified from expread.y by the Department of Computer Science at the
8    State University of New York at Buffalo, 1991.
9
10    This file is part of GDB.
11
12    This program is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3 of the License, or
15    (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
24
25 /* Parse an expression from text in a string,
26    and return the result as a  struct expression  pointer.
27    That structure contains arithmetic operations in reverse polish,
28    with constants represented by operations that are followed by special data.
29    See expression.h for the details of the format.
30    What is important here is that it can be built up sequentially
31    during the process of parsing; the lower levels of the tree always
32    come first in the result.  */
33
34 #include "defs.h"
35 #include <ctype.h>
36 #include "arch-utils.h"
37 #include "gdb_string.h"
38 #include "symtab.h"
39 #include "gdbtypes.h"
40 #include "frame.h"
41 #include "expression.h"
42 #include "value.h"
43 #include "command.h"
44 #include "language.h"
45 #include "f-lang.h"
46 #include "parser-defs.h"
47 #include "gdbcmd.h"
48 #include "symfile.h"            /* for overlay functions */
49 #include "inferior.h"
50 #include "doublest.h"
51 #include "gdb_assert.h"
52 #include "block.h"
53 #include "source.h"
54 #include "objfiles.h"
55 #include "exceptions.h"
56 #include "user-regs.h"
57
58 /* Standard set of definitions for printing, dumping, prefixifying,
59  * and evaluating expressions.  */
60
61 const struct exp_descriptor exp_descriptor_standard = 
62   {
63     print_subexp_standard,
64     operator_length_standard,
65     op_name_standard,
66     dump_subexp_body_standard,
67     evaluate_subexp_standard
68   };
69 \f
70 /* Global variables declared in parser-defs.h (and commented there).  */
71 struct expression *expout;
72 int expout_size;
73 int expout_ptr;
74 struct block *expression_context_block;
75 CORE_ADDR expression_context_pc;
76 struct block *innermost_block;
77 int arglist_len;
78 union type_stack_elt *type_stack;
79 int type_stack_depth, type_stack_size;
80 char *lexptr;
81 char *prev_lexptr;
82 int paren_depth;
83 int comma_terminates;
84
85 /* True if parsing an expression to find a field reference.  This is
86    only used by completion.  */
87 int in_parse_field;
88
89 /* The index of the last struct expression directly before a '.' or
90    '->'.  This is set when parsing and is only used when completing a
91    field name.  It is -1 if no dereference operation was found.  */
92 static int expout_last_struct = -1;
93
94 /* A temporary buffer for identifiers, so we can null-terminate them.
95
96    We allocate this with xrealloc.  parse_exp_1 used to allocate with
97    alloca, using the size of the whole expression as a conservative
98    estimate of the space needed.  However, macro expansion can
99    introduce names longer than the original expression; there's no
100    practical way to know beforehand how large that might be.  */
101 char *namecopy;
102 size_t namecopy_size;
103 \f
104 static int expressiondebug = 0;
105 static void
106 show_expressiondebug (struct ui_file *file, int from_tty,
107                       struct cmd_list_element *c, const char *value)
108 {
109   fprintf_filtered (file, _("Expression debugging is %s.\n"), value);
110 }
111
112 static void free_funcalls (void *ignore);
113
114 static int prefixify_expression (struct expression *);
115
116 static int prefixify_subexp (struct expression *, struct expression *, int,
117                              int);
118
119 static struct expression *parse_exp_in_context (char **, struct block *, int, 
120                                                 int, int *);
121
122 void _initialize_parse (void);
123
124 /* Data structure for saving values of arglist_len for function calls whose
125    arguments contain other function calls.  */
126
127 struct funcall
128   {
129     struct funcall *next;
130     int arglist_len;
131   };
132
133 static struct funcall *funcall_chain;
134
135 /* Begin counting arguments for a function call,
136    saving the data about any containing call.  */
137
138 void
139 start_arglist (void)
140 {
141   struct funcall *new;
142
143   new = (struct funcall *) xmalloc (sizeof (struct funcall));
144   new->next = funcall_chain;
145   new->arglist_len = arglist_len;
146   arglist_len = 0;
147   funcall_chain = new;
148 }
149
150 /* Return the number of arguments in a function call just terminated,
151    and restore the data for the containing function call.  */
152
153 int
154 end_arglist (void)
155 {
156   int val = arglist_len;
157   struct funcall *call = funcall_chain;
158   funcall_chain = call->next;
159   arglist_len = call->arglist_len;
160   xfree (call);
161   return val;
162 }
163
164 /* Free everything in the funcall chain.
165    Used when there is an error inside parsing.  */
166
167 static void
168 free_funcalls (void *ignore)
169 {
170   struct funcall *call, *next;
171
172   for (call = funcall_chain; call; call = next)
173     {
174       next = call->next;
175       xfree (call);
176     }
177 }
178 \f
179 /* This page contains the functions for adding data to the  struct expression
180    being constructed.  */
181
182 /* Add one element to the end of the expression.  */
183
184 /* To avoid a bug in the Sun 4 compiler, we pass things that can fit into
185    a register through here */
186
187 void
188 write_exp_elt (union exp_element expelt)
189 {
190   if (expout_ptr >= expout_size)
191     {
192       expout_size *= 2;
193       expout = (struct expression *)
194         xrealloc ((char *) expout, sizeof (struct expression)
195                   + EXP_ELEM_TO_BYTES (expout_size));
196     }
197   expout->elts[expout_ptr++] = expelt;
198 }
199
200 void
201 write_exp_elt_opcode (enum exp_opcode expelt)
202 {
203   union exp_element tmp;
204   memset (&tmp, 0, sizeof (union exp_element));
205
206   tmp.opcode = expelt;
207
208   write_exp_elt (tmp);
209 }
210
211 void
212 write_exp_elt_sym (struct symbol *expelt)
213 {
214   union exp_element tmp;
215   memset (&tmp, 0, sizeof (union exp_element));
216
217   tmp.symbol = expelt;
218
219   write_exp_elt (tmp);
220 }
221
222 void
223 write_exp_elt_block (struct block *b)
224 {
225   union exp_element tmp;
226   memset (&tmp, 0, sizeof (union exp_element));
227   tmp.block = b;
228   write_exp_elt (tmp);
229 }
230
231 void
232 write_exp_elt_objfile (struct objfile *objfile)
233 {
234   union exp_element tmp;
235   memset (&tmp, 0, sizeof (union exp_element));
236   tmp.objfile = objfile;
237   write_exp_elt (tmp);
238 }
239
240 void
241 write_exp_elt_longcst (LONGEST expelt)
242 {
243   union exp_element tmp;
244   memset (&tmp, 0, sizeof (union exp_element));
245
246   tmp.longconst = expelt;
247
248   write_exp_elt (tmp);
249 }
250
251 void
252 write_exp_elt_dblcst (DOUBLEST expelt)
253 {
254   union exp_element tmp;
255   memset (&tmp, 0, sizeof (union exp_element));
256
257   tmp.doubleconst = expelt;
258
259   write_exp_elt (tmp);
260 }
261
262 void
263 write_exp_elt_decfloatcst (gdb_byte expelt[16])
264 {
265   union exp_element tmp;
266   int index;
267
268   for (index = 0; index < 16; index++)
269     tmp.decfloatconst[index] = expelt[index];
270
271   write_exp_elt (tmp);
272 }
273
274 void
275 write_exp_elt_type (struct type *expelt)
276 {
277   union exp_element tmp;
278   memset (&tmp, 0, sizeof (union exp_element));
279
280   tmp.type = expelt;
281
282   write_exp_elt (tmp);
283 }
284
285 void
286 write_exp_elt_intern (struct internalvar *expelt)
287 {
288   union exp_element tmp;
289   memset (&tmp, 0, sizeof (union exp_element));
290
291   tmp.internalvar = expelt;
292
293   write_exp_elt (tmp);
294 }
295
296 /* Add a string constant to the end of the expression.
297
298    String constants are stored by first writing an expression element
299    that contains the length of the string, then stuffing the string
300    constant itself into however many expression elements are needed
301    to hold it, and then writing another expression element that contains
302    the length of the string.  I.E. an expression element at each end of
303    the string records the string length, so you can skip over the 
304    expression elements containing the actual string bytes from either
305    end of the string.  Note that this also allows gdb to handle
306    strings with embedded null bytes, as is required for some languages.
307
308    Don't be fooled by the fact that the string is null byte terminated,
309    this is strictly for the convenience of debugging gdb itself.
310    Gdb does not depend up the string being null terminated, since the
311    actual length is recorded in expression elements at each end of the
312    string.  The null byte is taken into consideration when computing how
313    many expression elements are required to hold the string constant, of
314    course. */
315
316
317 void
318 write_exp_string (struct stoken str)
319 {
320   int len = str.length;
321   int lenelt;
322   char *strdata;
323
324   /* Compute the number of expression elements required to hold the string
325      (including a null byte terminator), along with one expression element
326      at each end to record the actual string length (not including the
327      null byte terminator). */
328
329   lenelt = 2 + BYTES_TO_EXP_ELEM (len + 1);
330
331   /* Ensure that we have enough available expression elements to store
332      everything. */
333
334   if ((expout_ptr + lenelt) >= expout_size)
335     {
336       expout_size = max (expout_size * 2, expout_ptr + lenelt + 10);
337       expout = (struct expression *)
338         xrealloc ((char *) expout, (sizeof (struct expression)
339                                     + EXP_ELEM_TO_BYTES (expout_size)));
340     }
341
342   /* Write the leading length expression element (which advances the current
343      expression element index), then write the string constant followed by a
344      terminating null byte, and then write the trailing length expression
345      element. */
346
347   write_exp_elt_longcst ((LONGEST) len);
348   strdata = (char *) &expout->elts[expout_ptr];
349   memcpy (strdata, str.ptr, len);
350   *(strdata + len) = '\0';
351   expout_ptr += lenelt - 2;
352   write_exp_elt_longcst ((LONGEST) len);
353 }
354
355 /* Add a vector of string constants to the end of the expression.
356
357    This adds an OP_STRING operation, but encodes the contents
358    differently from write_exp_string.  The language is expected to
359    handle evaluation of this expression itself.
360    
361    After the usual OP_STRING header, TYPE is written into the
362    expression as a long constant.  The interpretation of this field is
363    up to the language evaluator.
364    
365    Next, each string in VEC is written.  The length is written as a
366    long constant, followed by the contents of the string.  */
367
368 void
369 write_exp_string_vector (int type, struct stoken_vector *vec)
370 {
371   int i, n_slots, len;
372
373   /* Compute the size.  We compute the size in number of slots to
374      avoid issues with string padding.  */
375   n_slots = 0;
376   for (i = 0; i < vec->len; ++i)
377     {
378       /* One slot for the length of this element, plus the number of
379          slots needed for this string.  */
380       n_slots += 1 + BYTES_TO_EXP_ELEM (vec->tokens[i].length);
381     }
382
383   /* One more slot for the type of the string.  */
384   ++n_slots;
385
386   /* Now compute a phony string length.  */
387   len = EXP_ELEM_TO_BYTES (n_slots) - 1;
388
389   n_slots += 4;
390   if ((expout_ptr + n_slots) >= expout_size)
391     {
392       expout_size = max (expout_size * 2, expout_ptr + n_slots + 10);
393       expout = (struct expression *)
394         xrealloc ((char *) expout, (sizeof (struct expression)
395                                     + EXP_ELEM_TO_BYTES (expout_size)));
396     }
397
398   write_exp_elt_opcode (OP_STRING);
399   write_exp_elt_longcst (len);
400   write_exp_elt_longcst (type);
401
402   for (i = 0; i < vec->len; ++i)
403     {
404       write_exp_elt_longcst (vec->tokens[i].length);
405       memcpy (&expout->elts[expout_ptr], vec->tokens[i].ptr,
406               vec->tokens[i].length);
407       expout_ptr += BYTES_TO_EXP_ELEM (vec->tokens[i].length);
408     }
409
410   write_exp_elt_longcst (len);
411   write_exp_elt_opcode (OP_STRING);
412 }
413
414 /* Add a bitstring constant to the end of the expression.
415
416    Bitstring constants are stored by first writing an expression element
417    that contains the length of the bitstring (in bits), then stuffing the
418    bitstring constant itself into however many expression elements are
419    needed to hold it, and then writing another expression element that
420    contains the length of the bitstring.  I.E. an expression element at
421    each end of the bitstring records the bitstring length, so you can skip
422    over the expression elements containing the actual bitstring bytes from
423    either end of the bitstring. */
424
425 void
426 write_exp_bitstring (struct stoken str)
427 {
428   int bits = str.length;        /* length in bits */
429   int len = (bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
430   int lenelt;
431   char *strdata;
432
433   /* Compute the number of expression elements required to hold the bitstring,
434      along with one expression element at each end to record the actual
435      bitstring length in bits. */
436
437   lenelt = 2 + BYTES_TO_EXP_ELEM (len);
438
439   /* Ensure that we have enough available expression elements to store
440      everything. */
441
442   if ((expout_ptr + lenelt) >= expout_size)
443     {
444       expout_size = max (expout_size * 2, expout_ptr + lenelt + 10);
445       expout = (struct expression *)
446         xrealloc ((char *) expout, (sizeof (struct expression)
447                                     + EXP_ELEM_TO_BYTES (expout_size)));
448     }
449
450   /* Write the leading length expression element (which advances the current
451      expression element index), then write the bitstring constant, and then
452      write the trailing length expression element. */
453
454   write_exp_elt_longcst ((LONGEST) bits);
455   strdata = (char *) &expout->elts[expout_ptr];
456   memcpy (strdata, str.ptr, len);
457   expout_ptr += lenelt - 2;
458   write_exp_elt_longcst ((LONGEST) bits);
459 }
460
461 /* Add the appropriate elements for a minimal symbol to the end of
462    the expression.  */
463
464 void
465 write_exp_msymbol (struct minimal_symbol *msymbol)
466 {
467   struct objfile *objfile = msymbol_objfile (msymbol);
468   struct gdbarch *gdbarch = get_objfile_arch (objfile);
469
470   CORE_ADDR addr = SYMBOL_VALUE_ADDRESS (msymbol);
471   struct obj_section *section = SYMBOL_OBJ_SECTION (msymbol);
472   enum minimal_symbol_type type = MSYMBOL_TYPE (msymbol);
473   CORE_ADDR pc;
474
475   /* The minimal symbol might point to a function descriptor;
476      resolve it to the actual code address instead.  */
477   pc = gdbarch_convert_from_func_ptr_addr (gdbarch, addr, &current_target);
478   if (pc != addr)
479     {
480       /* In this case, assume we have a code symbol instead of
481          a data symbol.  */
482       type = mst_text;
483       section = NULL;
484       addr = pc;
485     }
486
487   if (overlay_debugging)
488     addr = symbol_overlayed_address (addr, section);
489
490   write_exp_elt_opcode (OP_LONG);
491   /* Let's make the type big enough to hold a 64-bit address.  */
492   write_exp_elt_type (objfile_type (objfile)->builtin_core_addr);
493   write_exp_elt_longcst ((LONGEST) addr);
494   write_exp_elt_opcode (OP_LONG);
495
496   if (section && section->the_bfd_section->flags & SEC_THREAD_LOCAL)
497     {
498       write_exp_elt_opcode (UNOP_MEMVAL_TLS);
499       write_exp_elt_objfile (objfile);
500       write_exp_elt_type (objfile_type (objfile)->nodebug_tls_symbol);
501       write_exp_elt_opcode (UNOP_MEMVAL_TLS);
502       return;
503     }
504
505   write_exp_elt_opcode (UNOP_MEMVAL);
506   switch (type)
507     {
508     case mst_text:
509     case mst_file_text:
510     case mst_solib_trampoline:
511       write_exp_elt_type (objfile_type (objfile)->nodebug_text_symbol);
512       break;
513
514     case mst_data:
515     case mst_file_data:
516     case mst_bss:
517     case mst_file_bss:
518       write_exp_elt_type (objfile_type (objfile)->nodebug_data_symbol);
519       break;
520
521     default:
522       write_exp_elt_type (objfile_type (objfile)->nodebug_unknown_symbol);
523       break;
524     }
525   write_exp_elt_opcode (UNOP_MEMVAL);
526 }
527
528 /* Mark the current index as the starting location of a structure
529    expression.  This is used when completing on field names.  */
530
531 void
532 mark_struct_expression (void)
533 {
534   expout_last_struct = expout_ptr;
535 }
536
537 \f
538 /* Recognize tokens that start with '$'.  These include:
539
540    $regname     A native register name or a "standard
541    register name".
542
543    $variable    A convenience variable with a name chosen
544    by the user.
545
546    $digits              Value history with index <digits>, starting
547    from the first value which has index 1.
548
549    $$digits     Value history with index <digits> relative
550    to the last value.  I.E. $$0 is the last
551    value, $$1 is the one previous to that, $$2
552    is the one previous to $$1, etc.
553
554    $ | $0 | $$0 The last value in the value history.
555
556    $$           An abbreviation for the second to the last
557    value in the value history, I.E. $$1
558
559  */
560
561 void
562 write_dollar_variable (struct stoken str)
563 {
564   struct symbol *sym = NULL;
565   struct minimal_symbol *msym = NULL;
566   struct internalvar *isym = NULL;
567
568   /* Handle the tokens $digits; also $ (short for $0) and $$ (short for $$1)
569      and $$digits (equivalent to $<-digits> if you could type that). */
570
571   int negate = 0;
572   int i = 1;
573   /* Double dollar means negate the number and add -1 as well.
574      Thus $$ alone means -1.  */
575   if (str.length >= 2 && str.ptr[1] == '$')
576     {
577       negate = 1;
578       i = 2;
579     }
580   if (i == str.length)
581     {
582       /* Just dollars (one or two) */
583       i = -negate;
584       goto handle_last;
585     }
586   /* Is the rest of the token digits?  */
587   for (; i < str.length; i++)
588     if (!(str.ptr[i] >= '0' && str.ptr[i] <= '9'))
589       break;
590   if (i == str.length)
591     {
592       i = atoi (str.ptr + 1 + negate);
593       if (negate)
594         i = -i;
595       goto handle_last;
596     }
597
598   /* Handle tokens that refer to machine registers:
599      $ followed by a register name.  */
600   i = user_reg_map_name_to_regnum (parse_gdbarch,
601                                    str.ptr + 1, str.length - 1);
602   if (i >= 0)
603     goto handle_register;
604
605   /* Any names starting with $ are probably debugger internal variables.  */
606
607   isym = lookup_only_internalvar (copy_name (str) + 1);
608   if (isym)
609     {
610       write_exp_elt_opcode (OP_INTERNALVAR);
611       write_exp_elt_intern (isym);
612       write_exp_elt_opcode (OP_INTERNALVAR);
613       return;
614     }
615
616   /* On some systems, such as HP-UX and hppa-linux, certain system routines 
617      have names beginning with $ or $$.  Check for those, first. */
618
619   sym = lookup_symbol (copy_name (str), (struct block *) NULL,
620                        VAR_DOMAIN, (int *) NULL);
621   if (sym)
622     {
623       write_exp_elt_opcode (OP_VAR_VALUE);
624       write_exp_elt_block (block_found);        /* set by lookup_symbol */
625       write_exp_elt_sym (sym);
626       write_exp_elt_opcode (OP_VAR_VALUE);
627       return;
628     }
629   msym = lookup_minimal_symbol (copy_name (str), NULL, NULL);
630   if (msym)
631     {
632       write_exp_msymbol (msym);
633       return;
634     }
635
636   /* Any other names are assumed to be debugger internal variables.  */
637
638   write_exp_elt_opcode (OP_INTERNALVAR);
639   write_exp_elt_intern (create_internalvar (copy_name (str) + 1));
640   write_exp_elt_opcode (OP_INTERNALVAR);
641   return;
642 handle_last:
643   write_exp_elt_opcode (OP_LAST);
644   write_exp_elt_longcst ((LONGEST) i);
645   write_exp_elt_opcode (OP_LAST);
646   return;
647 handle_register:
648   write_exp_elt_opcode (OP_REGISTER);
649   str.length--;
650   str.ptr++;
651   write_exp_string (str);
652   write_exp_elt_opcode (OP_REGISTER);
653   return;
654 }
655
656
657 char *
658 find_template_name_end (char *p)
659 {
660   int depth = 1;
661   int just_seen_right = 0;
662   int just_seen_colon = 0;
663   int just_seen_space = 0;
664
665   if (!p || (*p != '<'))
666     return 0;
667
668   while (*++p)
669     {
670       switch (*p)
671         {
672         case '\'':
673         case '\"':
674         case '{':
675         case '}':
676           /* In future, may want to allow these?? */
677           return 0;
678         case '<':
679           depth++;              /* start nested template */
680           if (just_seen_colon || just_seen_right || just_seen_space)
681             return 0;           /* but not after : or :: or > or space */
682           break;
683         case '>':
684           if (just_seen_colon || just_seen_right)
685             return 0;           /* end a (nested?) template */
686           just_seen_right = 1;  /* but not after : or :: */
687           if (--depth == 0)     /* also disallow >>, insist on > > */
688             return ++p;         /* if outermost ended, return */
689           break;
690         case ':':
691           if (just_seen_space || (just_seen_colon > 1))
692             return 0;           /* nested class spec coming up */
693           just_seen_colon++;    /* we allow :: but not :::: */
694           break;
695         case ' ':
696           break;
697         default:
698           if (!((*p >= 'a' && *p <= 'z') ||     /* allow token chars */
699                 (*p >= 'A' && *p <= 'Z') ||
700                 (*p >= '0' && *p <= '9') ||
701                 (*p == '_') || (*p == ',') ||   /* commas for template args */
702                 (*p == '&') || (*p == '*') ||   /* pointer and ref types */
703                 (*p == '(') || (*p == ')') ||   /* function types */
704                 (*p == '[') || (*p == ']')))    /* array types */
705             return 0;
706         }
707       if (*p != ' ')
708         just_seen_space = 0;
709       if (*p != ':')
710         just_seen_colon = 0;
711       if (*p != '>')
712         just_seen_right = 0;
713     }
714   return 0;
715 }
716 \f
717
718
719 /* Return a null-terminated temporary copy of the name
720    of a string token.  */
721
722 char *
723 copy_name (struct stoken token)
724 {
725   /* Make sure there's enough space for the token.  */
726   if (namecopy_size < token.length + 1)
727     {
728       namecopy_size = token.length + 1;
729       namecopy = xrealloc (namecopy, token.length + 1);
730     }
731       
732   memcpy (namecopy, token.ptr, token.length);
733   namecopy[token.length] = 0;
734
735   return namecopy;
736 }
737 \f
738 /* Reverse an expression from suffix form (in which it is constructed)
739    to prefix form (in which we can conveniently print or execute it).
740    Ordinarily this always returns -1.  However, if EXPOUT_LAST_STRUCT
741    is not -1 (i.e., we are trying to complete a field name), it will
742    return the index of the subexpression which is the left-hand-side
743    of the struct operation at EXPOUT_LAST_STRUCT.  */
744
745 static int
746 prefixify_expression (struct expression *expr)
747 {
748   int len = sizeof (struct expression) + EXP_ELEM_TO_BYTES (expr->nelts);
749   struct expression *temp;
750   int inpos = expr->nelts, outpos = 0;
751
752   temp = (struct expression *) alloca (len);
753
754   /* Copy the original expression into temp.  */
755   memcpy (temp, expr, len);
756
757   return prefixify_subexp (temp, expr, inpos, outpos);
758 }
759
760 /* Return the number of exp_elements in the postfix subexpression 
761    of EXPR whose operator is at index ENDPOS - 1 in EXPR.  */
762
763 int
764 length_of_subexp (struct expression *expr, int endpos)
765 {
766   int oplen, args, i;
767
768   operator_length (expr, endpos, &oplen, &args);
769
770   while (args > 0)
771     {
772       oplen += length_of_subexp (expr, endpos - oplen);
773       args--;
774     }
775
776   return oplen;
777 }
778
779 /* Sets *OPLENP to the length of the operator whose (last) index is 
780    ENDPOS - 1 in EXPR, and sets *ARGSP to the number of arguments that
781    operator takes.  */
782
783 void
784 operator_length (struct expression *expr, int endpos, int *oplenp, int *argsp)
785 {
786   expr->language_defn->la_exp_desc->operator_length (expr, endpos,
787                                                      oplenp, argsp);
788 }
789
790 /* Default value for operator_length in exp_descriptor vectors.  */
791
792 void
793 operator_length_standard (struct expression *expr, int endpos,
794                           int *oplenp, int *argsp)
795 {
796   int oplen = 1;
797   int args = 0;
798   enum f90_range_type range_type;
799   int i;
800
801   if (endpos < 1)
802     error (_("?error in operator_length_standard"));
803
804   i = (int) expr->elts[endpos - 1].opcode;
805
806   switch (i)
807     {
808       /* C++  */
809     case OP_SCOPE:
810       oplen = longest_to_int (expr->elts[endpos - 2].longconst);
811       oplen = 5 + BYTES_TO_EXP_ELEM (oplen + 1);
812       break;
813
814     case OP_LONG:
815     case OP_DOUBLE:
816     case OP_DECFLOAT:
817     case OP_VAR_VALUE:
818       oplen = 4;
819       break;
820
821     case OP_TYPE:
822     case OP_BOOL:
823     case OP_LAST:
824     case OP_INTERNALVAR:
825       oplen = 3;
826       break;
827
828     case OP_COMPLEX:
829       oplen = 3;
830       args = 2;
831       break;
832
833     case OP_FUNCALL:
834     case OP_F77_UNDETERMINED_ARGLIST:
835       oplen = 3;
836       args = 1 + longest_to_int (expr->elts[endpos - 2].longconst);
837       break;
838
839     case TYPE_INSTANCE:
840       oplen = 4 + longest_to_int (expr->elts[endpos - 2].longconst);
841       args = 1;
842       break;
843
844     case OP_OBJC_MSGCALL:       /* Objective C message (method) call */
845       oplen = 4;
846       args = 1 + longest_to_int (expr->elts[endpos - 2].longconst);
847       break;
848
849     case UNOP_MAX:
850     case UNOP_MIN:
851       oplen = 3;
852       break;
853
854     case BINOP_VAL:
855     case UNOP_CAST:
856     case UNOP_MEMVAL:
857       oplen = 3;
858       args = 1;
859       break;
860
861     case UNOP_MEMVAL_TLS:
862       oplen = 4;
863       args = 1;
864       break;
865
866     case UNOP_ABS:
867     case UNOP_CAP:
868     case UNOP_CHR:
869     case UNOP_FLOAT:
870     case UNOP_HIGH:
871     case UNOP_ODD:
872     case UNOP_ORD:
873     case UNOP_TRUNC:
874       oplen = 1;
875       args = 1;
876       break;
877
878     case OP_LABELED:
879     case STRUCTOP_STRUCT:
880     case STRUCTOP_PTR:
881       args = 1;
882       /* fall through */
883     case OP_REGISTER:
884     case OP_M2_STRING:
885     case OP_STRING:
886     case OP_OBJC_NSSTRING:      /* Objective C Foundation Class NSString constant */
887     case OP_OBJC_SELECTOR:      /* Objective C "@selector" pseudo-op */
888     case OP_NAME:
889       oplen = longest_to_int (expr->elts[endpos - 2].longconst);
890       oplen = 4 + BYTES_TO_EXP_ELEM (oplen + 1);
891       break;
892
893     case OP_BITSTRING:
894       oplen = longest_to_int (expr->elts[endpos - 2].longconst);
895       oplen = (oplen + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
896       oplen = 4 + BYTES_TO_EXP_ELEM (oplen);
897       break;
898
899     case OP_ARRAY:
900       oplen = 4;
901       args = longest_to_int (expr->elts[endpos - 2].longconst);
902       args -= longest_to_int (expr->elts[endpos - 3].longconst);
903       args += 1;
904       break;
905
906     case TERNOP_COND:
907     case TERNOP_SLICE:
908     case TERNOP_SLICE_COUNT:
909       args = 3;
910       break;
911
912       /* Modula-2 */
913     case MULTI_SUBSCRIPT:
914       oplen = 3;
915       args = 1 + longest_to_int (expr->elts[endpos - 2].longconst);
916       break;
917
918     case BINOP_ASSIGN_MODIFY:
919       oplen = 3;
920       args = 2;
921       break;
922
923       /* C++ */
924     case OP_THIS:
925     case OP_OBJC_SELF:
926       oplen = 2;
927       break;
928
929     case OP_F90_RANGE:
930       oplen = 3;
931
932       range_type = longest_to_int (expr->elts[endpos - 2].longconst);
933       switch (range_type)
934         {
935         case LOW_BOUND_DEFAULT:
936         case HIGH_BOUND_DEFAULT:
937           args = 1;
938           break;
939         case BOTH_BOUND_DEFAULT:
940           args = 0;
941           break;
942         case NONE_BOUND_DEFAULT:
943           args = 2;
944           break;
945         }
946
947       break;
948
949     default:
950       args = 1 + (i < (int) BINOP_END);
951     }
952
953   *oplenp = oplen;
954   *argsp = args;
955 }
956
957 /* Copy the subexpression ending just before index INEND in INEXPR
958    into OUTEXPR, starting at index OUTBEG.
959    In the process, convert it from suffix to prefix form.
960    If EXPOUT_LAST_STRUCT is -1, then this function always returns -1.
961    Otherwise, it returns the index of the subexpression which is the
962    left-hand-side of the expression at EXPOUT_LAST_STRUCT.  */
963
964 static int
965 prefixify_subexp (struct expression *inexpr,
966                   struct expression *outexpr, int inend, int outbeg)
967 {
968   int oplen;
969   int args;
970   int i;
971   int *arglens;
972   enum exp_opcode opcode;
973   int result = -1;
974
975   operator_length (inexpr, inend, &oplen, &args);
976
977   /* Copy the final operator itself, from the end of the input
978      to the beginning of the output.  */
979   inend -= oplen;
980   memcpy (&outexpr->elts[outbeg], &inexpr->elts[inend],
981           EXP_ELEM_TO_BYTES (oplen));
982   outbeg += oplen;
983
984   if (expout_last_struct == inend)
985     result = outbeg - oplen;
986
987   /* Find the lengths of the arg subexpressions.  */
988   arglens = (int *) alloca (args * sizeof (int));
989   for (i = args - 1; i >= 0; i--)
990     {
991       oplen = length_of_subexp (inexpr, inend);
992       arglens[i] = oplen;
993       inend -= oplen;
994     }
995
996   /* Now copy each subexpression, preserving the order of
997      the subexpressions, but prefixifying each one.
998      In this loop, inend starts at the beginning of
999      the expression this level is working on
1000      and marches forward over the arguments.
1001      outbeg does similarly in the output.  */
1002   for (i = 0; i < args; i++)
1003     {
1004       int r;
1005       oplen = arglens[i];
1006       inend += oplen;
1007       r = prefixify_subexp (inexpr, outexpr, inend, outbeg);
1008       if (r != -1)
1009         {
1010           /* Return immediately.  We probably have only parsed a
1011              partial expression, so we don't want to try to reverse
1012              the other operands.  */
1013           return r;
1014         }
1015       outbeg += oplen;
1016     }
1017
1018   return result;
1019 }
1020 \f
1021 /* This page contains the two entry points to this file.  */
1022
1023 /* Read an expression from the string *STRINGPTR points to,
1024    parse it, and return a pointer to a  struct expression  that we malloc.
1025    Use block BLOCK as the lexical context for variable names;
1026    if BLOCK is zero, use the block of the selected stack frame.
1027    Meanwhile, advance *STRINGPTR to point after the expression,
1028    at the first nonwhite character that is not part of the expression
1029    (possibly a null character).
1030
1031    If COMMA is nonzero, stop if a comma is reached.  */
1032
1033 struct expression *
1034 parse_exp_1 (char **stringptr, struct block *block, int comma)
1035 {
1036   return parse_exp_in_context (stringptr, block, comma, 0, NULL);
1037 }
1038
1039 /* As for parse_exp_1, except that if VOID_CONTEXT_P, then
1040    no value is expected from the expression.
1041    OUT_SUBEXP is set when attempting to complete a field name; in this
1042    case it is set to the index of the subexpression on the
1043    left-hand-side of the struct op.  If not doing such completion, it
1044    is left untouched.  */
1045
1046 static struct expression *
1047 parse_exp_in_context (char **stringptr, struct block *block, int comma, 
1048                       int void_context_p, int *out_subexp)
1049 {
1050   volatile struct gdb_exception except;
1051   struct cleanup *old_chain;
1052   int subexp;
1053
1054   lexptr = *stringptr;
1055   prev_lexptr = NULL;
1056
1057   paren_depth = 0;
1058   type_stack_depth = 0;
1059   expout_last_struct = -1;
1060
1061   comma_terminates = comma;
1062
1063   if (lexptr == 0 || *lexptr == 0)
1064     error_no_arg (_("expression to compute"));
1065
1066   old_chain = make_cleanup (free_funcalls, 0 /*ignore*/);
1067   funcall_chain = 0;
1068
1069   expression_context_block = block;
1070
1071   /* If no context specified, try using the current frame, if any.  */
1072   if (!expression_context_block)
1073     expression_context_block = get_selected_block (&expression_context_pc);
1074   else
1075     expression_context_pc = BLOCK_START (expression_context_block);
1076
1077   /* Fall back to using the current source static context, if any.  */
1078
1079   if (!expression_context_block)
1080     {
1081       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
1082       if (cursal.symtab)
1083         expression_context_block
1084           = BLOCKVECTOR_BLOCK (BLOCKVECTOR (cursal.symtab), STATIC_BLOCK);
1085       if (expression_context_block)
1086         expression_context_pc = BLOCK_START (expression_context_block);
1087     }
1088
1089   expout_size = 10;
1090   expout_ptr = 0;
1091   expout = (struct expression *)
1092     xmalloc (sizeof (struct expression) + EXP_ELEM_TO_BYTES (expout_size));
1093   expout->language_defn = current_language;
1094   expout->gdbarch = get_current_arch ();
1095
1096   TRY_CATCH (except, RETURN_MASK_ALL)
1097     {
1098       if (current_language->la_parser ())
1099         current_language->la_error (NULL);
1100     }
1101   if (except.reason < 0)
1102     {
1103       if (! in_parse_field)
1104         {
1105           xfree (expout);
1106           throw_exception (except);
1107         }
1108     }
1109
1110   discard_cleanups (old_chain);
1111
1112   /* Record the actual number of expression elements, and then
1113      reallocate the expression memory so that we free up any
1114      excess elements. */
1115
1116   expout->nelts = expout_ptr;
1117   expout = (struct expression *)
1118     xrealloc ((char *) expout,
1119               sizeof (struct expression) + EXP_ELEM_TO_BYTES (expout_ptr));;
1120
1121   /* Convert expression from postfix form as generated by yacc
1122      parser, to a prefix form. */
1123
1124   if (expressiondebug)
1125     dump_raw_expression (expout, gdb_stdlog,
1126                          "before conversion to prefix form");
1127
1128   subexp = prefixify_expression (expout);
1129   if (out_subexp)
1130     *out_subexp = subexp;
1131
1132   current_language->la_post_parser (&expout, void_context_p);
1133
1134   if (expressiondebug)
1135     dump_prefix_expression (expout, gdb_stdlog);
1136
1137   *stringptr = lexptr;
1138   return expout;
1139 }
1140
1141 /* Parse STRING as an expression, and complain if this fails
1142    to use up all of the contents of STRING.  */
1143
1144 struct expression *
1145 parse_expression (char *string)
1146 {
1147   struct expression *exp;
1148   exp = parse_exp_1 (&string, 0, 0);
1149   if (*string)
1150     error (_("Junk after end of expression."));
1151   return exp;
1152 }
1153
1154 /* Parse STRING as an expression.  If parsing ends in the middle of a
1155    field reference, return the type of the left-hand-side of the
1156    reference; furthermore, if the parsing ends in the field name,
1157    return the field name in *NAME.  In all other cases, return NULL.
1158    Returned non-NULL *NAME must be freed by the caller.  */
1159
1160 struct type *
1161 parse_field_expression (char *string, char **name)
1162 {
1163   struct expression *exp = NULL;
1164   struct value *val;
1165   int subexp;
1166   volatile struct gdb_exception except;
1167
1168   TRY_CATCH (except, RETURN_MASK_ALL)
1169     {
1170       in_parse_field = 1;
1171       exp = parse_exp_in_context (&string, 0, 0, 0, &subexp);
1172     }
1173   in_parse_field = 0;
1174   if (except.reason < 0 || ! exp)
1175     return NULL;
1176   if (expout_last_struct == -1)
1177     {
1178       xfree (exp);
1179       return NULL;
1180     }
1181
1182   *name = extract_field_op (exp, &subexp);
1183   if (!*name)
1184     {
1185       xfree (exp);
1186       return NULL;
1187     }
1188   /* (*NAME) is a part of the EXP memory block freed below.  */
1189   *name = xstrdup (*name);
1190
1191   val = evaluate_subexpression_type (exp, subexp);
1192   xfree (exp);
1193
1194   return value_type (val);
1195 }
1196
1197 /* A post-parser that does nothing */
1198
1199 void
1200 null_post_parser (struct expression **exp, int void_context_p)
1201 {
1202 }
1203 \f
1204 /* Stuff for maintaining a stack of types.  Currently just used by C, but
1205    probably useful for any language which declares its types "backwards".  */
1206
1207 static void
1208 check_type_stack_depth (void)
1209 {
1210   if (type_stack_depth == type_stack_size)
1211     {
1212       type_stack_size *= 2;
1213       type_stack = (union type_stack_elt *)
1214         xrealloc ((char *) type_stack, type_stack_size * sizeof (*type_stack));
1215     }
1216 }
1217
1218 void
1219 push_type (enum type_pieces tp)
1220 {
1221   check_type_stack_depth ();
1222   type_stack[type_stack_depth++].piece = tp;
1223 }
1224
1225 void
1226 push_type_int (int n)
1227 {
1228   check_type_stack_depth ();
1229   type_stack[type_stack_depth++].int_val = n;
1230 }
1231
1232 void
1233 push_type_address_space (char *string)
1234 {
1235   push_type_int (address_space_name_to_int (parse_gdbarch, string));
1236 }
1237
1238 enum type_pieces
1239 pop_type (void)
1240 {
1241   if (type_stack_depth)
1242     return type_stack[--type_stack_depth].piece;
1243   return tp_end;
1244 }
1245
1246 int
1247 pop_type_int (void)
1248 {
1249   if (type_stack_depth)
1250     return type_stack[--type_stack_depth].int_val;
1251   /* "Can't happen".  */
1252   return 0;
1253 }
1254
1255 /* Pop the type stack and return the type which corresponds to FOLLOW_TYPE
1256    as modified by all the stuff on the stack.  */
1257 struct type *
1258 follow_types (struct type *follow_type)
1259 {
1260   int done = 0;
1261   int make_const = 0;
1262   int make_volatile = 0;
1263   int make_addr_space = 0;
1264   int array_size;
1265
1266   while (!done)
1267     switch (pop_type ())
1268       {
1269       case tp_end:
1270         done = 1;
1271         if (make_const)
1272           follow_type = make_cv_type (make_const, 
1273                                       TYPE_VOLATILE (follow_type), 
1274                                       follow_type, 0);
1275         if (make_volatile)
1276           follow_type = make_cv_type (TYPE_CONST (follow_type), 
1277                                       make_volatile, 
1278                                       follow_type, 0);
1279         if (make_addr_space)
1280           follow_type = make_type_with_address_space (follow_type, 
1281                                                       make_addr_space);
1282         make_const = make_volatile = 0;
1283         make_addr_space = 0;
1284         break;
1285       case tp_const:
1286         make_const = 1;
1287         break;
1288       case tp_volatile:
1289         make_volatile = 1;
1290         break;
1291       case tp_space_identifier:
1292         make_addr_space = pop_type_int ();
1293         break;
1294       case tp_pointer:
1295         follow_type = lookup_pointer_type (follow_type);
1296         if (make_const)
1297           follow_type = make_cv_type (make_const, 
1298                                       TYPE_VOLATILE (follow_type), 
1299                                       follow_type, 0);
1300         if (make_volatile)
1301           follow_type = make_cv_type (TYPE_CONST (follow_type), 
1302                                       make_volatile, 
1303                                       follow_type, 0);
1304         if (make_addr_space)
1305           follow_type = make_type_with_address_space (follow_type, 
1306                                                       make_addr_space);
1307         make_const = make_volatile = 0;
1308         make_addr_space = 0;
1309         break;
1310       case tp_reference:
1311         follow_type = lookup_reference_type (follow_type);
1312         if (make_const)
1313           follow_type = make_cv_type (make_const, 
1314                                       TYPE_VOLATILE (follow_type), 
1315                                       follow_type, 0);
1316         if (make_volatile)
1317           follow_type = make_cv_type (TYPE_CONST (follow_type), 
1318                                       make_volatile, 
1319                                       follow_type, 0);
1320         if (make_addr_space)
1321           follow_type = make_type_with_address_space (follow_type, 
1322                                                       make_addr_space);
1323         make_const = make_volatile = 0;
1324         make_addr_space = 0;
1325         break;
1326       case tp_array:
1327         array_size = pop_type_int ();
1328         /* FIXME-type-allocation: need a way to free this type when we are
1329            done with it.  */
1330         follow_type =
1331           lookup_array_range_type (follow_type,
1332                                    0, array_size >= 0 ? array_size - 1 : 0);
1333         if (array_size < 0)
1334           TYPE_ARRAY_UPPER_BOUND_IS_UNDEFINED (follow_type) = 1;
1335         break;
1336       case tp_function:
1337         /* FIXME-type-allocation: need a way to free this type when we are
1338            done with it.  */
1339         follow_type = lookup_function_type (follow_type);
1340         break;
1341       }
1342   return follow_type;
1343 }
1344 \f
1345 /* This function avoids direct calls to fprintf 
1346    in the parser generated debug code.  */
1347 void
1348 parser_fprintf (FILE *x, const char *y, ...)
1349
1350   va_list args;
1351   va_start (args, y);
1352   if (x == stderr)
1353     vfprintf_unfiltered (gdb_stderr, y, args); 
1354   else
1355     {
1356       fprintf_unfiltered (gdb_stderr, " Unknown FILE used.\n");
1357       vfprintf_unfiltered (gdb_stderr, y, args);
1358     }
1359   va_end (args);
1360 }
1361
1362 void
1363 _initialize_parse (void)
1364 {
1365   type_stack_size = 80;
1366   type_stack_depth = 0;
1367   type_stack = (union type_stack_elt *)
1368     xmalloc (type_stack_size * sizeof (*type_stack));
1369
1370   add_setshow_zinteger_cmd ("expression", class_maintenance,
1371                             &expressiondebug, _("\
1372 Set expression debugging."), _("\
1373 Show expression debugging."), _("\
1374 When non-zero, the internal representation of expressions will be printed."),
1375                             NULL,
1376                             show_expressiondebug,
1377                             &setdebuglist, &showdebuglist);
1378 }