* ada-lang.c (ada_evaluate_subexp): [OP_ATR_FIRST, OP_ATR_LAST]
[external/binutils.git] / gdb / ada-lang.c
1 /* Ada language support routines for GDB, the GNU debugger.  Copyright (C)
2
3    1992, 1993, 1994, 1997, 1998, 1999, 2000, 2003, 2004, 2005, 2007, 2008,
4    2009 Free Software Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21
22 #include "defs.h"
23 #include <stdio.h>
24 #include "gdb_string.h"
25 #include <ctype.h>
26 #include <stdarg.h>
27 #include "demangle.h"
28 #include "gdb_regex.h"
29 #include "frame.h"
30 #include "symtab.h"
31 #include "gdbtypes.h"
32 #include "gdbcmd.h"
33 #include "expression.h"
34 #include "parser-defs.h"
35 #include "language.h"
36 #include "c-lang.h"
37 #include "inferior.h"
38 #include "symfile.h"
39 #include "objfiles.h"
40 #include "breakpoint.h"
41 #include "gdbcore.h"
42 #include "hashtab.h"
43 #include "gdb_obstack.h"
44 #include "ada-lang.h"
45 #include "completer.h"
46 #include "gdb_stat.h"
47 #ifdef UI_OUT
48 #include "ui-out.h"
49 #endif
50 #include "block.h"
51 #include "infcall.h"
52 #include "dictionary.h"
53 #include "exceptions.h"
54 #include "annotate.h"
55 #include "valprint.h"
56 #include "source.h"
57 #include "observer.h"
58 #include "vec.h"
59
60 /* Define whether or not the C operator '/' truncates towards zero for
61    differently signed operands (truncation direction is undefined in C). 
62    Copied from valarith.c.  */
63
64 #ifndef TRUNCATION_TOWARDS_ZERO
65 #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2)
66 #endif
67
68 static void extract_string (CORE_ADDR addr, char *buf);
69
70 static void modify_general_field (char *, LONGEST, int, int);
71
72 static struct type *desc_base_type (struct type *);
73
74 static struct type *desc_bounds_type (struct type *);
75
76 static struct value *desc_bounds (struct value *);
77
78 static int fat_pntr_bounds_bitpos (struct type *);
79
80 static int fat_pntr_bounds_bitsize (struct type *);
81
82 static struct type *desc_data_type (struct type *);
83
84 static struct value *desc_data (struct value *);
85
86 static int fat_pntr_data_bitpos (struct type *);
87
88 static int fat_pntr_data_bitsize (struct type *);
89
90 static struct value *desc_one_bound (struct value *, int, int);
91
92 static int desc_bound_bitpos (struct type *, int, int);
93
94 static int desc_bound_bitsize (struct type *, int, int);
95
96 static struct type *desc_index_type (struct type *, int);
97
98 static int desc_arity (struct type *);
99
100 static int ada_type_match (struct type *, struct type *, int);
101
102 static int ada_args_match (struct symbol *, struct value **, int);
103
104 static struct value *ensure_lval (struct value *, CORE_ADDR *);
105
106 static struct value *convert_actual (struct value *, struct type *,
107                                      CORE_ADDR *);
108
109 static struct value *make_array_descriptor (struct type *, struct value *,
110                                             CORE_ADDR *);
111
112 static void ada_add_block_symbols (struct obstack *,
113                                    struct block *, const char *,
114                                    domain_enum, struct objfile *, int);
115
116 static int is_nonfunction (struct ada_symbol_info *, int);
117
118 static void add_defn_to_vec (struct obstack *, struct symbol *,
119                              struct block *);
120
121 static int num_defns_collected (struct obstack *);
122
123 static struct ada_symbol_info *defns_collected (struct obstack *, int);
124
125 static struct partial_symbol *ada_lookup_partial_symbol (struct partial_symtab
126                                                          *, const char *, int,
127                                                          domain_enum, int);
128
129 static struct symtab *symtab_for_sym (struct symbol *);
130
131 static struct value *resolve_subexp (struct expression **, int *, int,
132                                      struct type *);
133
134 static void replace_operator_with_call (struct expression **, int, int, int,
135                                         struct symbol *, struct block *);
136
137 static int possible_user_operator_p (enum exp_opcode, struct value **);
138
139 static char *ada_op_name (enum exp_opcode);
140
141 static const char *ada_decoded_op_name (enum exp_opcode);
142
143 static int numeric_type_p (struct type *);
144
145 static int integer_type_p (struct type *);
146
147 static int scalar_type_p (struct type *);
148
149 static int discrete_type_p (struct type *);
150
151 static enum ada_renaming_category parse_old_style_renaming (struct type *,
152                                                             const char **,
153                                                             int *,
154                                                             const char **);
155
156 static struct symbol *find_old_style_renaming_symbol (const char *,
157                                                       struct block *);
158
159 static struct type *ada_lookup_struct_elt_type (struct type *, char *,
160                                                 int, int, int *);
161
162 static struct value *evaluate_subexp (struct type *, struct expression *,
163                                       int *, enum noside);
164
165 static struct value *evaluate_subexp_type (struct expression *, int *);
166
167 static int is_dynamic_field (struct type *, int);
168
169 static struct type *to_fixed_variant_branch_type (struct type *,
170                                                   const gdb_byte *,
171                                                   CORE_ADDR, struct value *);
172
173 static struct type *to_fixed_array_type (struct type *, struct value *, int);
174
175 static struct type *to_fixed_range_type (char *, struct value *,
176                                          struct objfile *);
177
178 static struct type *to_static_fixed_type (struct type *);
179 static struct type *static_unwrap_type (struct type *type);
180
181 static struct value *unwrap_value (struct value *);
182
183 static struct type *packed_array_type (struct type *, long *);
184
185 static struct type *decode_packed_array_type (struct type *);
186
187 static struct value *decode_packed_array (struct value *);
188
189 static struct value *value_subscript_packed (struct value *, int,
190                                              struct value **);
191
192 static void move_bits (gdb_byte *, int, const gdb_byte *, int, int);
193
194 static struct value *coerce_unspec_val_to_type (struct value *,
195                                                 struct type *);
196
197 static struct value *get_var_value (char *, char *);
198
199 static int lesseq_defined_than (struct symbol *, struct symbol *);
200
201 static int equiv_types (struct type *, struct type *);
202
203 static int is_name_suffix (const char *);
204
205 static int wild_match (const char *, int, const char *);
206
207 static struct value *ada_coerce_ref (struct value *);
208
209 static LONGEST pos_atr (struct value *);
210
211 static struct value *value_pos_atr (struct type *, struct value *);
212
213 static struct value *value_val_atr (struct type *, struct value *);
214
215 static struct symbol *standard_lookup (const char *, const struct block *,
216                                        domain_enum);
217
218 static struct value *ada_search_struct_field (char *, struct value *, int,
219                                               struct type *);
220
221 static struct value *ada_value_primitive_field (struct value *, int, int,
222                                                 struct type *);
223
224 static int find_struct_field (char *, struct type *, int,
225                               struct type **, int *, int *, int *, int *);
226
227 static struct value *ada_to_fixed_value_create (struct type *, CORE_ADDR,
228                                                 struct value *);
229
230 static struct value *ada_to_fixed_value (struct value *);
231
232 static int ada_resolve_function (struct ada_symbol_info *, int,
233                                  struct value **, int, const char *,
234                                  struct type *);
235
236 static struct value *ada_coerce_to_simple_array (struct value *);
237
238 static int ada_is_direct_array_type (struct type *);
239
240 static void ada_language_arch_info (struct gdbarch *,
241                                     struct language_arch_info *);
242
243 static void check_size (const struct type *);
244
245 static struct value *ada_index_struct_field (int, struct value *, int,
246                                              struct type *);
247
248 static struct value *assign_aggregate (struct value *, struct value *, 
249                                        struct expression *, int *, enum noside);
250
251 static void aggregate_assign_from_choices (struct value *, struct value *, 
252                                            struct expression *,
253                                            int *, LONGEST *, int *,
254                                            int, LONGEST, LONGEST);
255
256 static void aggregate_assign_positional (struct value *, struct value *,
257                                          struct expression *,
258                                          int *, LONGEST *, int *, int,
259                                          LONGEST, LONGEST);
260
261
262 static void aggregate_assign_others (struct value *, struct value *,
263                                      struct expression *,
264                                      int *, LONGEST *, int, LONGEST, LONGEST);
265
266
267 static void add_component_interval (LONGEST, LONGEST, LONGEST *, int *, int);
268
269
270 static struct value *ada_evaluate_subexp (struct type *, struct expression *,
271                                           int *, enum noside);
272
273 static void ada_forward_operator_length (struct expression *, int, int *,
274                                          int *);
275 \f
276
277
278 /* Maximum-sized dynamic type.  */
279 static unsigned int varsize_limit;
280
281 /* FIXME: brobecker/2003-09-17: No longer a const because it is
282    returned by a function that does not return a const char *.  */
283 static char *ada_completer_word_break_characters =
284 #ifdef VMS
285   " \t\n!@#%^&*()+=|~`}{[]\";:?/,-";
286 #else
287   " \t\n!@#$%^&*()+=|~`}{[]\";:?/,-";
288 #endif
289
290 /* The name of the symbol to use to get the name of the main subprogram.  */
291 static const char ADA_MAIN_PROGRAM_SYMBOL_NAME[]
292   = "__gnat_ada_main_program_name";
293
294 /* Limit on the number of warnings to raise per expression evaluation.  */
295 static int warning_limit = 2;
296
297 /* Number of warning messages issued; reset to 0 by cleanups after
298    expression evaluation.  */
299 static int warnings_issued = 0;
300
301 static const char *known_runtime_file_name_patterns[] = {
302   ADA_KNOWN_RUNTIME_FILE_NAME_PATTERNS NULL
303 };
304
305 static const char *known_auxiliary_function_name_patterns[] = {
306   ADA_KNOWN_AUXILIARY_FUNCTION_NAME_PATTERNS NULL
307 };
308
309 /* Space for allocating results of ada_lookup_symbol_list.  */
310 static struct obstack symbol_list_obstack;
311
312                         /* Utilities */
313
314 /* Given DECODED_NAME a string holding a symbol name in its
315    decoded form (ie using the Ada dotted notation), returns
316    its unqualified name.  */
317
318 static const char *
319 ada_unqualified_name (const char *decoded_name)
320 {
321   const char *result = strrchr (decoded_name, '.');
322
323   if (result != NULL)
324     result++;                   /* Skip the dot...  */
325   else
326     result = decoded_name;
327
328   return result;
329 }
330
331 /* Return a string starting with '<', followed by STR, and '>'.
332    The result is good until the next call.  */
333
334 static char *
335 add_angle_brackets (const char *str)
336 {
337   static char *result = NULL;
338
339   xfree (result);
340   result = (char *) xmalloc ((strlen (str) + 3) * sizeof (char));
341
342   sprintf (result, "<%s>", str);
343   return result;
344 }
345
346 static char *
347 ada_get_gdb_completer_word_break_characters (void)
348 {
349   return ada_completer_word_break_characters;
350 }
351
352 /* Print an array element index using the Ada syntax.  */
353
354 static void
355 ada_print_array_index (struct value *index_value, struct ui_file *stream,
356                        const struct value_print_options *options)
357 {
358   LA_VALUE_PRINT (index_value, stream, options);
359   fprintf_filtered (stream, " => ");
360 }
361
362 /* Read the string located at ADDR from the inferior and store the
363    result into BUF.  */
364
365 static void
366 extract_string (CORE_ADDR addr, char *buf)
367 {
368   int char_index = 0;
369
370   /* Loop, reading one byte at a time, until we reach the '\000'
371      end-of-string marker.  */
372   do
373     {
374       target_read_memory (addr + char_index * sizeof (char),
375                           buf + char_index * sizeof (char), sizeof (char));
376       char_index++;
377     }
378   while (buf[char_index - 1] != '\000');
379 }
380
381 /* Assuming VECT points to an array of *SIZE objects of size
382    ELEMENT_SIZE, grow it to contain at least MIN_SIZE objects,
383    updating *SIZE as necessary and returning the (new) array.  */
384
385 void *
386 grow_vect (void *vect, size_t *size, size_t min_size, int element_size)
387 {
388   if (*size < min_size)
389     {
390       *size *= 2;
391       if (*size < min_size)
392         *size = min_size;
393       vect = xrealloc (vect, *size * element_size);
394     }
395   return vect;
396 }
397
398 /* True (non-zero) iff TARGET matches FIELD_NAME up to any trailing
399    suffix of FIELD_NAME beginning "___".  */
400
401 static int
402 field_name_match (const char *field_name, const char *target)
403 {
404   int len = strlen (target);
405   return
406     (strncmp (field_name, target, len) == 0
407      && (field_name[len] == '\0'
408          || (strncmp (field_name + len, "___", 3) == 0
409              && strcmp (field_name + strlen (field_name) - 6,
410                         "___XVN") != 0)));
411 }
412
413
414 /* Assuming TYPE is a TYPE_CODE_STRUCT or a TYPE_CODE_TYPDEF to
415    a TYPE_CODE_STRUCT, find the field whose name matches FIELD_NAME,
416    and return its index.  This function also handles fields whose name
417    have ___ suffixes because the compiler sometimes alters their name
418    by adding such a suffix to represent fields with certain constraints.
419    If the field could not be found, return a negative number if
420    MAYBE_MISSING is set.  Otherwise raise an error.  */
421
422 int
423 ada_get_field_index (const struct type *type, const char *field_name,
424                      int maybe_missing)
425 {
426   int fieldno;
427   struct type *struct_type = check_typedef ((struct type *) type);
428
429   for (fieldno = 0; fieldno < TYPE_NFIELDS (struct_type); fieldno++)
430     if (field_name_match (TYPE_FIELD_NAME (struct_type, fieldno), field_name))
431       return fieldno;
432
433   if (!maybe_missing)
434     error (_("Unable to find field %s in struct %s.  Aborting"),
435            field_name, TYPE_NAME (struct_type));
436
437   return -1;
438 }
439
440 /* The length of the prefix of NAME prior to any "___" suffix.  */
441
442 int
443 ada_name_prefix_len (const char *name)
444 {
445   if (name == NULL)
446     return 0;
447   else
448     {
449       const char *p = strstr (name, "___");
450       if (p == NULL)
451         return strlen (name);
452       else
453         return p - name;
454     }
455 }
456
457 /* Return non-zero if SUFFIX is a suffix of STR.
458    Return zero if STR is null.  */
459
460 static int
461 is_suffix (const char *str, const char *suffix)
462 {
463   int len1, len2;
464   if (str == NULL)
465     return 0;
466   len1 = strlen (str);
467   len2 = strlen (suffix);
468   return (len1 >= len2 && strcmp (str + len1 - len2, suffix) == 0);
469 }
470
471 /* The contents of value VAL, treated as a value of type TYPE.  The
472    result is an lval in memory if VAL is.  */
473
474 static struct value *
475 coerce_unspec_val_to_type (struct value *val, struct type *type)
476 {
477   type = ada_check_typedef (type);
478   if (value_type (val) == type)
479     return val;
480   else
481     {
482       struct value *result;
483
484       /* Make sure that the object size is not unreasonable before
485          trying to allocate some memory for it.  */
486       check_size (type);
487
488       result = allocate_value (type);
489       set_value_component_location (result, val);
490       set_value_bitsize (result, value_bitsize (val));
491       set_value_bitpos (result, value_bitpos (val));
492       VALUE_ADDRESS (result) += value_offset (val);
493       if (value_lazy (val)
494           || TYPE_LENGTH (type) > TYPE_LENGTH (value_type (val)))
495         set_value_lazy (result, 1);
496       else
497         memcpy (value_contents_raw (result), value_contents (val),
498                 TYPE_LENGTH (type));
499       return result;
500     }
501 }
502
503 static const gdb_byte *
504 cond_offset_host (const gdb_byte *valaddr, long offset)
505 {
506   if (valaddr == NULL)
507     return NULL;
508   else
509     return valaddr + offset;
510 }
511
512 static CORE_ADDR
513 cond_offset_target (CORE_ADDR address, long offset)
514 {
515   if (address == 0)
516     return 0;
517   else
518     return address + offset;
519 }
520
521 /* Issue a warning (as for the definition of warning in utils.c, but
522    with exactly one argument rather than ...), unless the limit on the
523    number of warnings has passed during the evaluation of the current
524    expression.  */
525
526 /* FIXME: cagney/2004-10-10: This function is mimicking the behavior
527    provided by "complaint".  */
528 static void lim_warning (const char *format, ...) ATTR_FORMAT (printf, 1, 2);
529
530 static void
531 lim_warning (const char *format, ...)
532 {
533   va_list args;
534   va_start (args, format);
535
536   warnings_issued += 1;
537   if (warnings_issued <= warning_limit)
538     vwarning (format, args);
539
540   va_end (args);
541 }
542
543 /* Issue an error if the size of an object of type T is unreasonable,
544    i.e. if it would be a bad idea to allocate a value of this type in
545    GDB.  */
546
547 static void
548 check_size (const struct type *type)
549 {
550   if (TYPE_LENGTH (type) > varsize_limit)
551     error (_("object size is larger than varsize-limit"));
552 }
553
554
555 /* Note: would have used MAX_OF_TYPE and MIN_OF_TYPE macros from
556    gdbtypes.h, but some of the necessary definitions in that file
557    seem to have gone missing. */
558
559 /* Maximum value of a SIZE-byte signed integer type. */
560 static LONGEST
561 max_of_size (int size)
562 {
563   LONGEST top_bit = (LONGEST) 1 << (size * 8 - 2);
564   return top_bit | (top_bit - 1);
565 }
566
567 /* Minimum value of a SIZE-byte signed integer type. */
568 static LONGEST
569 min_of_size (int size)
570 {
571   return -max_of_size (size) - 1;
572 }
573
574 /* Maximum value of a SIZE-byte unsigned integer type. */
575 static ULONGEST
576 umax_of_size (int size)
577 {
578   ULONGEST top_bit = (ULONGEST) 1 << (size * 8 - 1);
579   return top_bit | (top_bit - 1);
580 }
581
582 /* Maximum value of integral type T, as a signed quantity. */
583 static LONGEST
584 max_of_type (struct type *t)
585 {
586   if (TYPE_UNSIGNED (t))
587     return (LONGEST) umax_of_size (TYPE_LENGTH (t));
588   else
589     return max_of_size (TYPE_LENGTH (t));
590 }
591
592 /* Minimum value of integral type T, as a signed quantity. */
593 static LONGEST
594 min_of_type (struct type *t)
595 {
596   if (TYPE_UNSIGNED (t)) 
597     return 0;
598   else
599     return min_of_size (TYPE_LENGTH (t));
600 }
601
602 /* The largest value in the domain of TYPE, a discrete type, as an integer.  */
603 static LONGEST
604 discrete_type_high_bound (struct type *type)
605 {
606   switch (TYPE_CODE (type))
607     {
608     case TYPE_CODE_RANGE:
609       return TYPE_HIGH_BOUND (type);
610     case TYPE_CODE_ENUM:
611       return TYPE_FIELD_BITPOS (type, TYPE_NFIELDS (type) - 1);
612     case TYPE_CODE_BOOL:
613       return 1;
614     case TYPE_CODE_CHAR:
615     case TYPE_CODE_INT:
616       return max_of_type (type);
617     default:
618       error (_("Unexpected type in discrete_type_high_bound."));
619     }
620 }
621
622 /* The largest value in the domain of TYPE, a discrete type, as an integer.  */
623 static LONGEST
624 discrete_type_low_bound (struct type *type)
625 {
626   switch (TYPE_CODE (type))
627     {
628     case TYPE_CODE_RANGE:
629       return TYPE_LOW_BOUND (type);
630     case TYPE_CODE_ENUM:
631       return TYPE_FIELD_BITPOS (type, 0);
632     case TYPE_CODE_BOOL:
633       return 0;
634     case TYPE_CODE_CHAR:
635     case TYPE_CODE_INT:
636       return min_of_type (type);
637     default:
638       error (_("Unexpected type in discrete_type_low_bound."));
639     }
640 }
641
642 /* The identity on non-range types.  For range types, the underlying
643    non-range scalar type.  */
644
645 static struct type *
646 base_type (struct type *type)
647 {
648   while (type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE)
649     {
650       if (type == TYPE_TARGET_TYPE (type) || TYPE_TARGET_TYPE (type) == NULL)
651         return type;
652       type = TYPE_TARGET_TYPE (type);
653     }
654   return type;
655 }
656 \f
657
658                                 /* Language Selection */
659
660 /* If the main program is in Ada, return language_ada, otherwise return LANG
661    (the main program is in Ada iif the adainit symbol is found).
662
663    MAIN_PST is not used.  */
664
665 enum language
666 ada_update_initial_language (enum language lang,
667                              struct partial_symtab *main_pst)
668 {
669   if (lookup_minimal_symbol ("adainit", (const char *) NULL,
670                              (struct objfile *) NULL) != NULL)
671     return language_ada;
672
673   return lang;
674 }
675
676 /* If the main procedure is written in Ada, then return its name.
677    The result is good until the next call.  Return NULL if the main
678    procedure doesn't appear to be in Ada.  */
679
680 char *
681 ada_main_name (void)
682 {
683   struct minimal_symbol *msym;
684   CORE_ADDR main_program_name_addr;
685   static char main_program_name[1024];
686
687   /* For Ada, the name of the main procedure is stored in a specific
688      string constant, generated by the binder.  Look for that symbol,
689      extract its address, and then read that string.  If we didn't find
690      that string, then most probably the main procedure is not written
691      in Ada.  */
692   msym = lookup_minimal_symbol (ADA_MAIN_PROGRAM_SYMBOL_NAME, NULL, NULL);
693
694   if (msym != NULL)
695     {
696       main_program_name_addr = SYMBOL_VALUE_ADDRESS (msym);
697       if (main_program_name_addr == 0)
698         error (_("Invalid address for Ada main program name."));
699
700       extract_string (main_program_name_addr, main_program_name);
701       return main_program_name;
702     }
703
704   /* The main procedure doesn't seem to be in Ada.  */
705   return NULL;
706 }
707 \f
708                                 /* Symbols */
709
710 /* Table of Ada operators and their GNAT-encoded names.  Last entry is pair
711    of NULLs.  */
712
713 const struct ada_opname_map ada_opname_table[] = {
714   {"Oadd", "\"+\"", BINOP_ADD},
715   {"Osubtract", "\"-\"", BINOP_SUB},
716   {"Omultiply", "\"*\"", BINOP_MUL},
717   {"Odivide", "\"/\"", BINOP_DIV},
718   {"Omod", "\"mod\"", BINOP_MOD},
719   {"Orem", "\"rem\"", BINOP_REM},
720   {"Oexpon", "\"**\"", BINOP_EXP},
721   {"Olt", "\"<\"", BINOP_LESS},
722   {"Ole", "\"<=\"", BINOP_LEQ},
723   {"Ogt", "\">\"", BINOP_GTR},
724   {"Oge", "\">=\"", BINOP_GEQ},
725   {"Oeq", "\"=\"", BINOP_EQUAL},
726   {"One", "\"/=\"", BINOP_NOTEQUAL},
727   {"Oand", "\"and\"", BINOP_BITWISE_AND},
728   {"Oor", "\"or\"", BINOP_BITWISE_IOR},
729   {"Oxor", "\"xor\"", BINOP_BITWISE_XOR},
730   {"Oconcat", "\"&\"", BINOP_CONCAT},
731   {"Oabs", "\"abs\"", UNOP_ABS},
732   {"Onot", "\"not\"", UNOP_LOGICAL_NOT},
733   {"Oadd", "\"+\"", UNOP_PLUS},
734   {"Osubtract", "\"-\"", UNOP_NEG},
735   {NULL, NULL}
736 };
737
738 /* The "encoded" form of DECODED, according to GNAT conventions.
739    The result is valid until the next call to ada_encode.  */
740
741 char *
742 ada_encode (const char *decoded)
743 {
744   static char *encoding_buffer = NULL;
745   static size_t encoding_buffer_size = 0;
746   const char *p;
747   int k;
748
749   if (decoded == NULL)
750     return NULL;
751
752   GROW_VECT (encoding_buffer, encoding_buffer_size,
753              2 * strlen (decoded) + 10);
754
755   k = 0;
756   for (p = decoded; *p != '\0'; p += 1)
757     {
758       if (*p == '.')
759         {
760           encoding_buffer[k] = encoding_buffer[k + 1] = '_';
761           k += 2;
762         }
763       else if (*p == '"')
764         {
765           const struct ada_opname_map *mapping;
766
767           for (mapping = ada_opname_table;
768                mapping->encoded != NULL
769                && strncmp (mapping->decoded, p,
770                            strlen (mapping->decoded)) != 0; mapping += 1)
771             ;
772           if (mapping->encoded == NULL)
773             error (_("invalid Ada operator name: %s"), p);
774           strcpy (encoding_buffer + k, mapping->encoded);
775           k += strlen (mapping->encoded);
776           break;
777         }
778       else
779         {
780           encoding_buffer[k] = *p;
781           k += 1;
782         }
783     }
784
785   encoding_buffer[k] = '\0';
786   return encoding_buffer;
787 }
788
789 /* Return NAME folded to lower case, or, if surrounded by single
790    quotes, unfolded, but with the quotes stripped away.  Result good
791    to next call.  */
792
793 char *
794 ada_fold_name (const char *name)
795 {
796   static char *fold_buffer = NULL;
797   static size_t fold_buffer_size = 0;
798
799   int len = strlen (name);
800   GROW_VECT (fold_buffer, fold_buffer_size, len + 1);
801
802   if (name[0] == '\'')
803     {
804       strncpy (fold_buffer, name + 1, len - 2);
805       fold_buffer[len - 2] = '\000';
806     }
807   else
808     {
809       int i;
810       for (i = 0; i <= len; i += 1)
811         fold_buffer[i] = tolower (name[i]);
812     }
813
814   return fold_buffer;
815 }
816
817 /* Return nonzero if C is either a digit or a lowercase alphabet character.  */
818
819 static int
820 is_lower_alphanum (const char c)
821 {
822   return (isdigit (c) || (isalpha (c) && islower (c)));
823 }
824
825 /* Remove either of these suffixes:
826      . .{DIGIT}+
827      . ${DIGIT}+
828      . ___{DIGIT}+
829      . __{DIGIT}+.
830    These are suffixes introduced by the compiler for entities such as
831    nested subprogram for instance, in order to avoid name clashes.
832    They do not serve any purpose for the debugger.  */
833
834 static void
835 ada_remove_trailing_digits (const char *encoded, int *len)
836 {
837   if (*len > 1 && isdigit (encoded[*len - 1]))
838     {
839       int i = *len - 2;
840       while (i > 0 && isdigit (encoded[i]))
841         i--;
842       if (i >= 0 && encoded[i] == '.')
843         *len = i;
844       else if (i >= 0 && encoded[i] == '$')
845         *len = i;
846       else if (i >= 2 && strncmp (encoded + i - 2, "___", 3) == 0)
847         *len = i - 2;
848       else if (i >= 1 && strncmp (encoded + i - 1, "__", 2) == 0)
849         *len = i - 1;
850     }
851 }
852
853 /* Remove the suffix introduced by the compiler for protected object
854    subprograms.  */
855
856 static void
857 ada_remove_po_subprogram_suffix (const char *encoded, int *len)
858 {
859   /* Remove trailing N.  */
860
861   /* Protected entry subprograms are broken into two
862      separate subprograms: The first one is unprotected, and has
863      a 'N' suffix; the second is the protected version, and has
864      the 'P' suffix. The second calls the first one after handling
865      the protection.  Since the P subprograms are internally generated,
866      we leave these names undecoded, giving the user a clue that this
867      entity is internal.  */
868
869   if (*len > 1
870       && encoded[*len - 1] == 'N'
871       && (isdigit (encoded[*len - 2]) || islower (encoded[*len - 2])))
872     *len = *len - 1;
873 }
874
875 /* If ENCODED follows the GNAT entity encoding conventions, then return
876    the decoded form of ENCODED.  Otherwise, return "<%s>" where "%s" is
877    replaced by ENCODED.
878
879    The resulting string is valid until the next call of ada_decode.
880    If the string is unchanged by decoding, the original string pointer
881    is returned.  */
882
883 const char *
884 ada_decode (const char *encoded)
885 {
886   int i, j;
887   int len0;
888   const char *p;
889   char *decoded;
890   int at_start_name;
891   static char *decoding_buffer = NULL;
892   static size_t decoding_buffer_size = 0;
893
894   /* The name of the Ada main procedure starts with "_ada_".
895      This prefix is not part of the decoded name, so skip this part
896      if we see this prefix.  */
897   if (strncmp (encoded, "_ada_", 5) == 0)
898     encoded += 5;
899
900   /* If the name starts with '_', then it is not a properly encoded
901      name, so do not attempt to decode it.  Similarly, if the name
902      starts with '<', the name should not be decoded.  */
903   if (encoded[0] == '_' || encoded[0] == '<')
904     goto Suppress;
905
906   len0 = strlen (encoded);
907
908   ada_remove_trailing_digits (encoded, &len0);
909   ada_remove_po_subprogram_suffix (encoded, &len0);
910
911   /* Remove the ___X.* suffix if present.  Do not forget to verify that
912      the suffix is located before the current "end" of ENCODED.  We want
913      to avoid re-matching parts of ENCODED that have previously been
914      marked as discarded (by decrementing LEN0).  */
915   p = strstr (encoded, "___");
916   if (p != NULL && p - encoded < len0 - 3)
917     {
918       if (p[3] == 'X')
919         len0 = p - encoded;
920       else
921         goto Suppress;
922     }
923
924   /* Remove any trailing TKB suffix.  It tells us that this symbol
925      is for the body of a task, but that information does not actually
926      appear in the decoded name.  */
927
928   if (len0 > 3 && strncmp (encoded + len0 - 3, "TKB", 3) == 0)
929     len0 -= 3;
930
931   /* Remove trailing "B" suffixes.  */
932   /* FIXME: brobecker/2006-04-19: Not sure what this are used for...  */
933
934   if (len0 > 1 && strncmp (encoded + len0 - 1, "B", 1) == 0)
935     len0 -= 1;
936
937   /* Make decoded big enough for possible expansion by operator name.  */
938
939   GROW_VECT (decoding_buffer, decoding_buffer_size, 2 * len0 + 1);
940   decoded = decoding_buffer;
941
942   /* Remove trailing __{digit}+ or trailing ${digit}+.  */
943
944   if (len0 > 1 && isdigit (encoded[len0 - 1]))
945     {
946       i = len0 - 2;
947       while ((i >= 0 && isdigit (encoded[i]))
948              || (i >= 1 && encoded[i] == '_' && isdigit (encoded[i - 1])))
949         i -= 1;
950       if (i > 1 && encoded[i] == '_' && encoded[i - 1] == '_')
951         len0 = i - 1;
952       else if (encoded[i] == '$')
953         len0 = i;
954     }
955
956   /* The first few characters that are not alphabetic are not part
957      of any encoding we use, so we can copy them over verbatim.  */
958
959   for (i = 0, j = 0; i < len0 && !isalpha (encoded[i]); i += 1, j += 1)
960     decoded[j] = encoded[i];
961
962   at_start_name = 1;
963   while (i < len0)
964     {
965       /* Is this a symbol function?  */
966       if (at_start_name && encoded[i] == 'O')
967         {
968           int k;
969           for (k = 0; ada_opname_table[k].encoded != NULL; k += 1)
970             {
971               int op_len = strlen (ada_opname_table[k].encoded);
972               if ((strncmp (ada_opname_table[k].encoded + 1, encoded + i + 1,
973                             op_len - 1) == 0)
974                   && !isalnum (encoded[i + op_len]))
975                 {
976                   strcpy (decoded + j, ada_opname_table[k].decoded);
977                   at_start_name = 0;
978                   i += op_len;
979                   j += strlen (ada_opname_table[k].decoded);
980                   break;
981                 }
982             }
983           if (ada_opname_table[k].encoded != NULL)
984             continue;
985         }
986       at_start_name = 0;
987
988       /* Replace "TK__" with "__", which will eventually be translated
989          into "." (just below).  */
990
991       if (i < len0 - 4 && strncmp (encoded + i, "TK__", 4) == 0)
992         i += 2;
993
994       /* Replace "__B_{DIGITS}+__" sequences by "__", which will eventually
995          be translated into "." (just below).  These are internal names
996          generated for anonymous blocks inside which our symbol is nested.  */
997
998       if (len0 - i > 5 && encoded [i] == '_' && encoded [i+1] == '_'
999           && encoded [i+2] == 'B' && encoded [i+3] == '_'
1000           && isdigit (encoded [i+4]))
1001         {
1002           int k = i + 5;
1003           
1004           while (k < len0 && isdigit (encoded[k]))
1005             k++;  /* Skip any extra digit.  */
1006
1007           /* Double-check that the "__B_{DIGITS}+" sequence we found
1008              is indeed followed by "__".  */
1009           if (len0 - k > 2 && encoded [k] == '_' && encoded [k+1] == '_')
1010             i = k;
1011         }
1012
1013       /* Remove _E{DIGITS}+[sb] */
1014
1015       /* Just as for protected object subprograms, there are 2 categories
1016          of subprograms created by the compiler for each entry. The first
1017          one implements the actual entry code, and has a suffix following
1018          the convention above; the second one implements the barrier and
1019          uses the same convention as above, except that the 'E' is replaced
1020          by a 'B'.
1021
1022          Just as above, we do not decode the name of barrier functions
1023          to give the user a clue that the code he is debugging has been
1024          internally generated.  */
1025
1026       if (len0 - i > 3 && encoded [i] == '_' && encoded[i+1] == 'E'
1027           && isdigit (encoded[i+2]))
1028         {
1029           int k = i + 3;
1030
1031           while (k < len0 && isdigit (encoded[k]))
1032             k++;
1033
1034           if (k < len0
1035               && (encoded[k] == 'b' || encoded[k] == 's'))
1036             {
1037               k++;
1038               /* Just as an extra precaution, make sure that if this
1039                  suffix is followed by anything else, it is a '_'.
1040                  Otherwise, we matched this sequence by accident.  */
1041               if (k == len0
1042                   || (k < len0 && encoded[k] == '_'))
1043                 i = k;
1044             }
1045         }
1046
1047       /* Remove trailing "N" in [a-z0-9]+N__.  The N is added by
1048          the GNAT front-end in protected object subprograms.  */
1049
1050       if (i < len0 + 3
1051           && encoded[i] == 'N' && encoded[i+1] == '_' && encoded[i+2] == '_')
1052         {
1053           /* Backtrack a bit up until we reach either the begining of
1054              the encoded name, or "__".  Make sure that we only find
1055              digits or lowercase characters.  */
1056           const char *ptr = encoded + i - 1;
1057
1058           while (ptr >= encoded && is_lower_alphanum (ptr[0]))
1059             ptr--;
1060           if (ptr < encoded
1061               || (ptr > encoded && ptr[0] == '_' && ptr[-1] == '_'))
1062             i++;
1063         }
1064
1065       if (encoded[i] == 'X' && i != 0 && isalnum (encoded[i - 1]))
1066         {
1067           /* This is a X[bn]* sequence not separated from the previous
1068              part of the name with a non-alpha-numeric character (in other
1069              words, immediately following an alpha-numeric character), then
1070              verify that it is placed at the end of the encoded name.  If
1071              not, then the encoding is not valid and we should abort the
1072              decoding.  Otherwise, just skip it, it is used in body-nested
1073              package names.  */
1074           do
1075             i += 1;
1076           while (i < len0 && (encoded[i] == 'b' || encoded[i] == 'n'));
1077           if (i < len0)
1078             goto Suppress;
1079         }
1080       else if (i < len0 - 2 && encoded[i] == '_' && encoded[i + 1] == '_')
1081         {
1082          /* Replace '__' by '.'.  */
1083           decoded[j] = '.';
1084           at_start_name = 1;
1085           i += 2;
1086           j += 1;
1087         }
1088       else
1089         {
1090           /* It's a character part of the decoded name, so just copy it
1091              over.  */
1092           decoded[j] = encoded[i];
1093           i += 1;
1094           j += 1;
1095         }
1096     }
1097   decoded[j] = '\000';
1098
1099   /* Decoded names should never contain any uppercase character.
1100      Double-check this, and abort the decoding if we find one.  */
1101
1102   for (i = 0; decoded[i] != '\0'; i += 1)
1103     if (isupper (decoded[i]) || decoded[i] == ' ')
1104       goto Suppress;
1105
1106   if (strcmp (decoded, encoded) == 0)
1107     return encoded;
1108   else
1109     return decoded;
1110
1111 Suppress:
1112   GROW_VECT (decoding_buffer, decoding_buffer_size, strlen (encoded) + 3);
1113   decoded = decoding_buffer;
1114   if (encoded[0] == '<')
1115     strcpy (decoded, encoded);
1116   else
1117     sprintf (decoded, "<%s>", encoded);
1118   return decoded;
1119
1120 }
1121
1122 /* Table for keeping permanent unique copies of decoded names.  Once
1123    allocated, names in this table are never released.  While this is a
1124    storage leak, it should not be significant unless there are massive
1125    changes in the set of decoded names in successive versions of a 
1126    symbol table loaded during a single session.  */
1127 static struct htab *decoded_names_store;
1128
1129 /* Returns the decoded name of GSYMBOL, as for ada_decode, caching it
1130    in the language-specific part of GSYMBOL, if it has not been
1131    previously computed.  Tries to save the decoded name in the same
1132    obstack as GSYMBOL, if possible, and otherwise on the heap (so that,
1133    in any case, the decoded symbol has a lifetime at least that of
1134    GSYMBOL).  
1135    The GSYMBOL parameter is "mutable" in the C++ sense: logically
1136    const, but nevertheless modified to a semantically equivalent form
1137    when a decoded name is cached in it.
1138 */
1139
1140 char *
1141 ada_decode_symbol (const struct general_symbol_info *gsymbol)
1142 {
1143   char **resultp =
1144     (char **) &gsymbol->language_specific.cplus_specific.demangled_name;
1145   if (*resultp == NULL)
1146     {
1147       const char *decoded = ada_decode (gsymbol->name);
1148       if (gsymbol->obj_section != NULL)
1149         {
1150           struct objfile *objf = gsymbol->obj_section->objfile;
1151           *resultp = obsavestring (decoded, strlen (decoded),
1152                                    &objf->objfile_obstack);
1153         }
1154       /* Sometimes, we can't find a corresponding objfile, in which
1155          case, we put the result on the heap.  Since we only decode
1156          when needed, we hope this usually does not cause a
1157          significant memory leak (FIXME).  */
1158       if (*resultp == NULL)
1159         {
1160           char **slot = (char **) htab_find_slot (decoded_names_store,
1161                                                   decoded, INSERT);
1162           if (*slot == NULL)
1163             *slot = xstrdup (decoded);
1164           *resultp = *slot;
1165         }
1166     }
1167
1168   return *resultp;
1169 }
1170
1171 static char *
1172 ada_la_decode (const char *encoded, int options)
1173 {
1174   return xstrdup (ada_decode (encoded));
1175 }
1176
1177 /* Returns non-zero iff SYM_NAME matches NAME, ignoring any trailing
1178    suffixes that encode debugging information or leading _ada_ on
1179    SYM_NAME (see is_name_suffix commentary for the debugging
1180    information that is ignored).  If WILD, then NAME need only match a
1181    suffix of SYM_NAME minus the same suffixes.  Also returns 0 if
1182    either argument is NULL.  */
1183
1184 static int
1185 ada_match_name (const char *sym_name, const char *name, int wild)
1186 {
1187   if (sym_name == NULL || name == NULL)
1188     return 0;
1189   else if (wild)
1190     return wild_match (name, strlen (name), sym_name);
1191   else
1192     {
1193       int len_name = strlen (name);
1194       return (strncmp (sym_name, name, len_name) == 0
1195               && is_name_suffix (sym_name + len_name))
1196         || (strncmp (sym_name, "_ada_", 5) == 0
1197             && strncmp (sym_name + 5, name, len_name) == 0
1198             && is_name_suffix (sym_name + len_name + 5));
1199     }
1200 }
1201 \f
1202
1203                                 /* Arrays */
1204
1205 /* Names of MAX_ADA_DIMENS bounds in P_BOUNDS fields of array descriptors.  */
1206
1207 static char *bound_name[] = {
1208   "LB0", "UB0", "LB1", "UB1", "LB2", "UB2", "LB3", "UB3",
1209   "LB4", "UB4", "LB5", "UB5", "LB6", "UB6", "LB7", "UB7"
1210 };
1211
1212 /* Maximum number of array dimensions we are prepared to handle.  */
1213
1214 #define MAX_ADA_DIMENS (sizeof(bound_name) / (2*sizeof(char *)))
1215
1216 /* Like modify_field, but allows bitpos > wordlength.  */
1217
1218 static void
1219 modify_general_field (char *addr, LONGEST fieldval, int bitpos, int bitsize)
1220 {
1221   modify_field (addr + bitpos / 8, fieldval, bitpos % 8, bitsize);
1222 }
1223
1224
1225 /* The desc_* routines return primitive portions of array descriptors
1226    (fat pointers).  */
1227
1228 /* The descriptor or array type, if any, indicated by TYPE; removes
1229    level of indirection, if needed.  */
1230
1231 static struct type *
1232 desc_base_type (struct type *type)
1233 {
1234   if (type == NULL)
1235     return NULL;
1236   type = ada_check_typedef (type);
1237   if (type != NULL
1238       && (TYPE_CODE (type) == TYPE_CODE_PTR
1239           || TYPE_CODE (type) == TYPE_CODE_REF))
1240     return ada_check_typedef (TYPE_TARGET_TYPE (type));
1241   else
1242     return type;
1243 }
1244
1245 /* True iff TYPE indicates a "thin" array pointer type.  */
1246
1247 static int
1248 is_thin_pntr (struct type *type)
1249 {
1250   return
1251     is_suffix (ada_type_name (desc_base_type (type)), "___XUT")
1252     || is_suffix (ada_type_name (desc_base_type (type)), "___XUT___XVE");
1253 }
1254
1255 /* The descriptor type for thin pointer type TYPE.  */
1256
1257 static struct type *
1258 thin_descriptor_type (struct type *type)
1259 {
1260   struct type *base_type = desc_base_type (type);
1261   if (base_type == NULL)
1262     return NULL;
1263   if (is_suffix (ada_type_name (base_type), "___XVE"))
1264     return base_type;
1265   else
1266     {
1267       struct type *alt_type = ada_find_parallel_type (base_type, "___XVE");
1268       if (alt_type == NULL)
1269         return base_type;
1270       else
1271         return alt_type;
1272     }
1273 }
1274
1275 /* A pointer to the array data for thin-pointer value VAL.  */
1276
1277 static struct value *
1278 thin_data_pntr (struct value *val)
1279 {
1280   struct type *type = value_type (val);
1281   if (TYPE_CODE (type) == TYPE_CODE_PTR)
1282     return value_cast (desc_data_type (thin_descriptor_type (type)),
1283                        value_copy (val));
1284   else
1285     return value_from_longest (desc_data_type (thin_descriptor_type (type)),
1286                                VALUE_ADDRESS (val) + value_offset (val));
1287 }
1288
1289 /* True iff TYPE indicates a "thick" array pointer type.  */
1290
1291 static int
1292 is_thick_pntr (struct type *type)
1293 {
1294   type = desc_base_type (type);
1295   return (type != NULL && TYPE_CODE (type) == TYPE_CODE_STRUCT
1296           && lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL);
1297 }
1298
1299 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1300    pointer to one, the type of its bounds data; otherwise, NULL.  */
1301
1302 static struct type *
1303 desc_bounds_type (struct type *type)
1304 {
1305   struct type *r;
1306
1307   type = desc_base_type (type);
1308
1309   if (type == NULL)
1310     return NULL;
1311   else if (is_thin_pntr (type))
1312     {
1313       type = thin_descriptor_type (type);
1314       if (type == NULL)
1315         return NULL;
1316       r = lookup_struct_elt_type (type, "BOUNDS", 1);
1317       if (r != NULL)
1318         return ada_check_typedef (r);
1319     }
1320   else if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1321     {
1322       r = lookup_struct_elt_type (type, "P_BOUNDS", 1);
1323       if (r != NULL)
1324         return ada_check_typedef (TYPE_TARGET_TYPE (ada_check_typedef (r)));
1325     }
1326   return NULL;
1327 }
1328
1329 /* If ARR is an array descriptor (fat or thin pointer), or pointer to
1330    one, a pointer to its bounds data.   Otherwise NULL.  */
1331
1332 static struct value *
1333 desc_bounds (struct value *arr)
1334 {
1335   struct type *type = ada_check_typedef (value_type (arr));
1336   if (is_thin_pntr (type))
1337     {
1338       struct type *bounds_type =
1339         desc_bounds_type (thin_descriptor_type (type));
1340       LONGEST addr;
1341
1342       if (bounds_type == NULL)
1343         error (_("Bad GNAT array descriptor"));
1344
1345       /* NOTE: The following calculation is not really kosher, but
1346          since desc_type is an XVE-encoded type (and shouldn't be),
1347          the correct calculation is a real pain.  FIXME (and fix GCC).  */
1348       if (TYPE_CODE (type) == TYPE_CODE_PTR)
1349         addr = value_as_long (arr);
1350       else
1351         addr = VALUE_ADDRESS (arr) + value_offset (arr);
1352
1353       return
1354         value_from_longest (lookup_pointer_type (bounds_type),
1355                             addr - TYPE_LENGTH (bounds_type));
1356     }
1357
1358   else if (is_thick_pntr (type))
1359     return value_struct_elt (&arr, NULL, "P_BOUNDS", NULL,
1360                              _("Bad GNAT array descriptor"));
1361   else
1362     return NULL;
1363 }
1364
1365 /* If TYPE is the type of an array-descriptor (fat pointer),  the bit
1366    position of the field containing the address of the bounds data.  */
1367
1368 static int
1369 fat_pntr_bounds_bitpos (struct type *type)
1370 {
1371   return TYPE_FIELD_BITPOS (desc_base_type (type), 1);
1372 }
1373
1374 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1375    size of the field containing the address of the bounds data.  */
1376
1377 static int
1378 fat_pntr_bounds_bitsize (struct type *type)
1379 {
1380   type = desc_base_type (type);
1381
1382   if (TYPE_FIELD_BITSIZE (type, 1) > 0)
1383     return TYPE_FIELD_BITSIZE (type, 1);
1384   else
1385     return 8 * TYPE_LENGTH (ada_check_typedef (TYPE_FIELD_TYPE (type, 1)));
1386 }
1387
1388 /* If TYPE is the type of an array descriptor (fat or thin pointer) or a
1389    pointer to one, the type of its array data (a
1390    pointer-to-array-with-no-bounds type); otherwise, NULL.  Use
1391    ada_type_of_array to get an array type with bounds data.  */
1392
1393 static struct type *
1394 desc_data_type (struct type *type)
1395 {
1396   type = desc_base_type (type);
1397
1398   /* NOTE: The following is bogus; see comment in desc_bounds.  */
1399   if (is_thin_pntr (type))
1400     return lookup_pointer_type
1401       (desc_base_type (TYPE_FIELD_TYPE (thin_descriptor_type (type), 1)));
1402   else if (is_thick_pntr (type))
1403     return lookup_struct_elt_type (type, "P_ARRAY", 1);
1404   else
1405     return NULL;
1406 }
1407
1408 /* If ARR is an array descriptor (fat or thin pointer), a pointer to
1409    its array data.  */
1410
1411 static struct value *
1412 desc_data (struct value *arr)
1413 {
1414   struct type *type = value_type (arr);
1415   if (is_thin_pntr (type))
1416     return thin_data_pntr (arr);
1417   else if (is_thick_pntr (type))
1418     return value_struct_elt (&arr, NULL, "P_ARRAY", NULL,
1419                              _("Bad GNAT array descriptor"));
1420   else
1421     return NULL;
1422 }
1423
1424
1425 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1426    position of the field containing the address of the data.  */
1427
1428 static int
1429 fat_pntr_data_bitpos (struct type *type)
1430 {
1431   return TYPE_FIELD_BITPOS (desc_base_type (type), 0);
1432 }
1433
1434 /* If TYPE is the type of an array-descriptor (fat pointer), the bit
1435    size of the field containing the address of the data.  */
1436
1437 static int
1438 fat_pntr_data_bitsize (struct type *type)
1439 {
1440   type = desc_base_type (type);
1441
1442   if (TYPE_FIELD_BITSIZE (type, 0) > 0)
1443     return TYPE_FIELD_BITSIZE (type, 0);
1444   else
1445     return TARGET_CHAR_BIT * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 0));
1446 }
1447
1448 /* If BOUNDS is an array-bounds structure (or pointer to one), return
1449    the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1450    bound, if WHICH is 1.  The first bound is I=1.  */
1451
1452 static struct value *
1453 desc_one_bound (struct value *bounds, int i, int which)
1454 {
1455   return value_struct_elt (&bounds, NULL, bound_name[2 * i + which - 2], NULL,
1456                            _("Bad GNAT array descriptor bounds"));
1457 }
1458
1459 /* If BOUNDS is an array-bounds structure type, return the bit position
1460    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1461    bound, if WHICH is 1.  The first bound is I=1.  */
1462
1463 static int
1464 desc_bound_bitpos (struct type *type, int i, int which)
1465 {
1466   return TYPE_FIELD_BITPOS (desc_base_type (type), 2 * i + which - 2);
1467 }
1468
1469 /* If BOUNDS is an array-bounds structure type, return the bit field size
1470    of the Ith lower bound stored in it, if WHICH is 0, and the Ith upper
1471    bound, if WHICH is 1.  The first bound is I=1.  */
1472
1473 static int
1474 desc_bound_bitsize (struct type *type, int i, int which)
1475 {
1476   type = desc_base_type (type);
1477
1478   if (TYPE_FIELD_BITSIZE (type, 2 * i + which - 2) > 0)
1479     return TYPE_FIELD_BITSIZE (type, 2 * i + which - 2);
1480   else
1481     return 8 * TYPE_LENGTH (TYPE_FIELD_TYPE (type, 2 * i + which - 2));
1482 }
1483
1484 /* If TYPE is the type of an array-bounds structure, the type of its
1485    Ith bound (numbering from 1).  Otherwise, NULL.  */
1486
1487 static struct type *
1488 desc_index_type (struct type *type, int i)
1489 {
1490   type = desc_base_type (type);
1491
1492   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1493     return lookup_struct_elt_type (type, bound_name[2 * i - 2], 1);
1494   else
1495     return NULL;
1496 }
1497
1498 /* The number of index positions in the array-bounds type TYPE.
1499    Return 0 if TYPE is NULL.  */
1500
1501 static int
1502 desc_arity (struct type *type)
1503 {
1504   type = desc_base_type (type);
1505
1506   if (type != NULL)
1507     return TYPE_NFIELDS (type) / 2;
1508   return 0;
1509 }
1510
1511 /* Non-zero iff TYPE is a simple array type (not a pointer to one) or 
1512    an array descriptor type (representing an unconstrained array
1513    type).  */
1514
1515 static int
1516 ada_is_direct_array_type (struct type *type)
1517 {
1518   if (type == NULL)
1519     return 0;
1520   type = ada_check_typedef (type);
1521   return (TYPE_CODE (type) == TYPE_CODE_ARRAY
1522           || ada_is_array_descriptor_type (type));
1523 }
1524
1525 /* Non-zero iff TYPE represents any kind of array in Ada, or a pointer
1526  * to one. */
1527
1528 static int
1529 ada_is_array_type (struct type *type)
1530 {
1531   while (type != NULL 
1532          && (TYPE_CODE (type) == TYPE_CODE_PTR 
1533              || TYPE_CODE (type) == TYPE_CODE_REF))
1534     type = TYPE_TARGET_TYPE (type);
1535   return ada_is_direct_array_type (type);
1536 }
1537
1538 /* Non-zero iff TYPE is a simple array type or pointer to one.  */
1539
1540 int
1541 ada_is_simple_array_type (struct type *type)
1542 {
1543   if (type == NULL)
1544     return 0;
1545   type = ada_check_typedef (type);
1546   return (TYPE_CODE (type) == TYPE_CODE_ARRAY
1547           || (TYPE_CODE (type) == TYPE_CODE_PTR
1548               && TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_ARRAY));
1549 }
1550
1551 /* Non-zero iff TYPE belongs to a GNAT array descriptor.  */
1552
1553 int
1554 ada_is_array_descriptor_type (struct type *type)
1555 {
1556   struct type *data_type = desc_data_type (type);
1557
1558   if (type == NULL)
1559     return 0;
1560   type = ada_check_typedef (type);
1561   return
1562     data_type != NULL
1563     && ((TYPE_CODE (data_type) == TYPE_CODE_PTR
1564          && TYPE_TARGET_TYPE (data_type) != NULL
1565          && TYPE_CODE (TYPE_TARGET_TYPE (data_type)) == TYPE_CODE_ARRAY)
1566         || TYPE_CODE (data_type) == TYPE_CODE_ARRAY)
1567     && desc_arity (desc_bounds_type (type)) > 0;
1568 }
1569
1570 /* Non-zero iff type is a partially mal-formed GNAT array
1571    descriptor.  FIXME: This is to compensate for some problems with
1572    debugging output from GNAT.  Re-examine periodically to see if it
1573    is still needed.  */
1574
1575 int
1576 ada_is_bogus_array_descriptor (struct type *type)
1577 {
1578   return
1579     type != NULL
1580     && TYPE_CODE (type) == TYPE_CODE_STRUCT
1581     && (lookup_struct_elt_type (type, "P_BOUNDS", 1) != NULL
1582         || lookup_struct_elt_type (type, "P_ARRAY", 1) != NULL)
1583     && !ada_is_array_descriptor_type (type);
1584 }
1585
1586
1587 /* If ARR has a record type in the form of a standard GNAT array descriptor,
1588    (fat pointer) returns the type of the array data described---specifically,
1589    a pointer-to-array type.  If BOUNDS is non-zero, the bounds data are filled
1590    in from the descriptor; otherwise, they are left unspecified.  If
1591    the ARR denotes a null array descriptor and BOUNDS is non-zero,
1592    returns NULL.  The result is simply the type of ARR if ARR is not
1593    a descriptor.  */
1594 struct type *
1595 ada_type_of_array (struct value *arr, int bounds)
1596 {
1597   if (ada_is_packed_array_type (value_type (arr)))
1598     return decode_packed_array_type (value_type (arr));
1599
1600   if (!ada_is_array_descriptor_type (value_type (arr)))
1601     return value_type (arr);
1602
1603   if (!bounds)
1604     return
1605       ada_check_typedef (TYPE_TARGET_TYPE (desc_data_type (value_type (arr))));
1606   else
1607     {
1608       struct type *elt_type;
1609       int arity;
1610       struct value *descriptor;
1611       struct objfile *objf = TYPE_OBJFILE (value_type (arr));
1612
1613       elt_type = ada_array_element_type (value_type (arr), -1);
1614       arity = ada_array_arity (value_type (arr));
1615
1616       if (elt_type == NULL || arity == 0)
1617         return ada_check_typedef (value_type (arr));
1618
1619       descriptor = desc_bounds (arr);
1620       if (value_as_long (descriptor) == 0)
1621         return NULL;
1622       while (arity > 0)
1623         {
1624           struct type *range_type = alloc_type (objf);
1625           struct type *array_type = alloc_type (objf);
1626           struct value *low = desc_one_bound (descriptor, arity, 0);
1627           struct value *high = desc_one_bound (descriptor, arity, 1);
1628           arity -= 1;
1629
1630           create_range_type (range_type, value_type (low),
1631                              longest_to_int (value_as_long (low)),
1632                              longest_to_int (value_as_long (high)));
1633           elt_type = create_array_type (array_type, elt_type, range_type);
1634         }
1635
1636       return lookup_pointer_type (elt_type);
1637     }
1638 }
1639
1640 /* If ARR does not represent an array, returns ARR unchanged.
1641    Otherwise, returns either a standard GDB array with bounds set
1642    appropriately or, if ARR is a non-null fat pointer, a pointer to a standard
1643    GDB array.  Returns NULL if ARR is a null fat pointer.  */
1644
1645 struct value *
1646 ada_coerce_to_simple_array_ptr (struct value *arr)
1647 {
1648   if (ada_is_array_descriptor_type (value_type (arr)))
1649     {
1650       struct type *arrType = ada_type_of_array (arr, 1);
1651       if (arrType == NULL)
1652         return NULL;
1653       return value_cast (arrType, value_copy (desc_data (arr)));
1654     }
1655   else if (ada_is_packed_array_type (value_type (arr)))
1656     return decode_packed_array (arr);
1657   else
1658     return arr;
1659 }
1660
1661 /* If ARR does not represent an array, returns ARR unchanged.
1662    Otherwise, returns a standard GDB array describing ARR (which may
1663    be ARR itself if it already is in the proper form).  */
1664
1665 static struct value *
1666 ada_coerce_to_simple_array (struct value *arr)
1667 {
1668   if (ada_is_array_descriptor_type (value_type (arr)))
1669     {
1670       struct value *arrVal = ada_coerce_to_simple_array_ptr (arr);
1671       if (arrVal == NULL)
1672         error (_("Bounds unavailable for null array pointer."));
1673       check_size (TYPE_TARGET_TYPE (value_type (arrVal)));
1674       return value_ind (arrVal);
1675     }
1676   else if (ada_is_packed_array_type (value_type (arr)))
1677     return decode_packed_array (arr);
1678   else
1679     return arr;
1680 }
1681
1682 /* If TYPE represents a GNAT array type, return it translated to an
1683    ordinary GDB array type (possibly with BITSIZE fields indicating
1684    packing).  For other types, is the identity.  */
1685
1686 struct type *
1687 ada_coerce_to_simple_array_type (struct type *type)
1688 {
1689   struct value *mark = value_mark ();
1690   struct value *dummy = value_from_longest (builtin_type_int32, 0);
1691   struct type *result;
1692   deprecated_set_value_type (dummy, type);
1693   result = ada_type_of_array (dummy, 0);
1694   value_free_to_mark (mark);
1695   return result;
1696 }
1697
1698 /* Non-zero iff TYPE represents a standard GNAT packed-array type.  */
1699
1700 int
1701 ada_is_packed_array_type (struct type *type)
1702 {
1703   if (type == NULL)
1704     return 0;
1705   type = desc_base_type (type);
1706   type = ada_check_typedef (type);
1707   return
1708     ada_type_name (type) != NULL
1709     && strstr (ada_type_name (type), "___XP") != NULL;
1710 }
1711
1712 /* Given that TYPE is a standard GDB array type with all bounds filled
1713    in, and that the element size of its ultimate scalar constituents
1714    (that is, either its elements, or, if it is an array of arrays, its
1715    elements' elements, etc.) is *ELT_BITS, return an identical type,
1716    but with the bit sizes of its elements (and those of any
1717    constituent arrays) recorded in the BITSIZE components of its
1718    TYPE_FIELD_BITSIZE values, and with *ELT_BITS set to its total size
1719    in bits.  */
1720
1721 static struct type *
1722 packed_array_type (struct type *type, long *elt_bits)
1723 {
1724   struct type *new_elt_type;
1725   struct type *new_type;
1726   LONGEST low_bound, high_bound;
1727
1728   type = ada_check_typedef (type);
1729   if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
1730     return type;
1731
1732   new_type = alloc_type (TYPE_OBJFILE (type));
1733   new_elt_type = packed_array_type (ada_check_typedef (TYPE_TARGET_TYPE (type)),
1734                                     elt_bits);
1735   create_array_type (new_type, new_elt_type, TYPE_INDEX_TYPE (type));
1736   TYPE_FIELD_BITSIZE (new_type, 0) = *elt_bits;
1737   TYPE_NAME (new_type) = ada_type_name (type);
1738
1739   if (get_discrete_bounds (TYPE_INDEX_TYPE (type),
1740                            &low_bound, &high_bound) < 0)
1741     low_bound = high_bound = 0;
1742   if (high_bound < low_bound)
1743     *elt_bits = TYPE_LENGTH (new_type) = 0;
1744   else
1745     {
1746       *elt_bits *= (high_bound - low_bound + 1);
1747       TYPE_LENGTH (new_type) =
1748         (*elt_bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
1749     }
1750
1751   TYPE_FIXED_INSTANCE (new_type) = 1;
1752   return new_type;
1753 }
1754
1755 /* The array type encoded by TYPE, where ada_is_packed_array_type (TYPE).  */
1756
1757 static struct type *
1758 decode_packed_array_type (struct type *type)
1759 {
1760   struct symbol *sym;
1761   struct block **blocks;
1762   char *raw_name = ada_type_name (ada_check_typedef (type));
1763   char *name;
1764   char *tail;
1765   struct type *shadow_type;
1766   long bits;
1767   int i, n;
1768
1769   if (!raw_name)
1770     raw_name = ada_type_name (desc_base_type (type));
1771
1772   if (!raw_name)
1773     return NULL;
1774
1775   name = (char *) alloca (strlen (raw_name) + 1);
1776   tail = strstr (raw_name, "___XP");
1777   type = desc_base_type (type);
1778
1779   memcpy (name, raw_name, tail - raw_name);
1780   name[tail - raw_name] = '\000';
1781
1782   sym = standard_lookup (name, get_selected_block (0), VAR_DOMAIN);
1783   if (sym == NULL || SYMBOL_TYPE (sym) == NULL)
1784     {
1785       lim_warning (_("could not find bounds information on packed array"));
1786       return NULL;
1787     }
1788   shadow_type = SYMBOL_TYPE (sym);
1789   CHECK_TYPEDEF (shadow_type);
1790
1791   if (TYPE_CODE (shadow_type) != TYPE_CODE_ARRAY)
1792     {
1793       lim_warning (_("could not understand bounds information on packed array"));
1794       return NULL;
1795     }
1796
1797   if (sscanf (tail + sizeof ("___XP") - 1, "%ld", &bits) != 1)
1798     {
1799       lim_warning
1800         (_("could not understand bit size information on packed array"));
1801       return NULL;
1802     }
1803
1804   return packed_array_type (shadow_type, &bits);
1805 }
1806
1807 /* Given that ARR is a struct value *indicating a GNAT packed array,
1808    returns a simple array that denotes that array.  Its type is a
1809    standard GDB array type except that the BITSIZEs of the array
1810    target types are set to the number of bits in each element, and the
1811    type length is set appropriately.  */
1812
1813 static struct value *
1814 decode_packed_array (struct value *arr)
1815 {
1816   struct type *type;
1817
1818   arr = ada_coerce_ref (arr);
1819   if (TYPE_CODE (value_type (arr)) == TYPE_CODE_PTR)
1820     arr = ada_value_ind (arr);
1821
1822   type = decode_packed_array_type (value_type (arr));
1823   if (type == NULL)
1824     {
1825       error (_("can't unpack array"));
1826       return NULL;
1827     }
1828
1829   if (gdbarch_bits_big_endian (current_gdbarch)
1830       && ada_is_modular_type (value_type (arr)))
1831     {
1832        /* This is a (right-justified) modular type representing a packed
1833          array with no wrapper.  In order to interpret the value through
1834          the (left-justified) packed array type we just built, we must
1835          first left-justify it.  */
1836       int bit_size, bit_pos;
1837       ULONGEST mod;
1838
1839       mod = ada_modulus (value_type (arr)) - 1;
1840       bit_size = 0;
1841       while (mod > 0)
1842         {
1843           bit_size += 1;
1844           mod >>= 1;
1845         }
1846       bit_pos = HOST_CHAR_BIT * TYPE_LENGTH (value_type (arr)) - bit_size;
1847       arr = ada_value_primitive_packed_val (arr, NULL,
1848                                             bit_pos / HOST_CHAR_BIT,
1849                                             bit_pos % HOST_CHAR_BIT,
1850                                             bit_size,
1851                                             type);
1852     }
1853
1854   return coerce_unspec_val_to_type (arr, type);
1855 }
1856
1857
1858 /* The value of the element of packed array ARR at the ARITY indices
1859    given in IND.   ARR must be a simple array.  */
1860
1861 static struct value *
1862 value_subscript_packed (struct value *arr, int arity, struct value **ind)
1863 {
1864   int i;
1865   int bits, elt_off, bit_off;
1866   long elt_total_bit_offset;
1867   struct type *elt_type;
1868   struct value *v;
1869
1870   bits = 0;
1871   elt_total_bit_offset = 0;
1872   elt_type = ada_check_typedef (value_type (arr));
1873   for (i = 0; i < arity; i += 1)
1874     {
1875       if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY
1876           || TYPE_FIELD_BITSIZE (elt_type, 0) == 0)
1877         error
1878           (_("attempt to do packed indexing of something other than a packed array"));
1879       else
1880         {
1881           struct type *range_type = TYPE_INDEX_TYPE (elt_type);
1882           LONGEST lowerbound, upperbound;
1883           LONGEST idx;
1884
1885           if (get_discrete_bounds (range_type, &lowerbound, &upperbound) < 0)
1886             {
1887               lim_warning (_("don't know bounds of array"));
1888               lowerbound = upperbound = 0;
1889             }
1890
1891           idx = pos_atr (ind[i]);
1892           if (idx < lowerbound || idx > upperbound)
1893             lim_warning (_("packed array index %ld out of bounds"), (long) idx);
1894           bits = TYPE_FIELD_BITSIZE (elt_type, 0);
1895           elt_total_bit_offset += (idx - lowerbound) * bits;
1896           elt_type = ada_check_typedef (TYPE_TARGET_TYPE (elt_type));
1897         }
1898     }
1899   elt_off = elt_total_bit_offset / HOST_CHAR_BIT;
1900   bit_off = elt_total_bit_offset % HOST_CHAR_BIT;
1901
1902   v = ada_value_primitive_packed_val (arr, NULL, elt_off, bit_off,
1903                                       bits, elt_type);
1904   return v;
1905 }
1906
1907 /* Non-zero iff TYPE includes negative integer values.  */
1908
1909 static int
1910 has_negatives (struct type *type)
1911 {
1912   switch (TYPE_CODE (type))
1913     {
1914     default:
1915       return 0;
1916     case TYPE_CODE_INT:
1917       return !TYPE_UNSIGNED (type);
1918     case TYPE_CODE_RANGE:
1919       return TYPE_LOW_BOUND (type) < 0;
1920     }
1921 }
1922
1923
1924 /* Create a new value of type TYPE from the contents of OBJ starting
1925    at byte OFFSET, and bit offset BIT_OFFSET within that byte,
1926    proceeding for BIT_SIZE bits.  If OBJ is an lval in memory, then
1927    assigning through the result will set the field fetched from.  
1928    VALADDR is ignored unless OBJ is NULL, in which case,
1929    VALADDR+OFFSET must address the start of storage containing the 
1930    packed value.  The value returned  in this case is never an lval.
1931    Assumes 0 <= BIT_OFFSET < HOST_CHAR_BIT.  */
1932
1933 struct value *
1934 ada_value_primitive_packed_val (struct value *obj, const gdb_byte *valaddr,
1935                                 long offset, int bit_offset, int bit_size,
1936                                 struct type *type)
1937 {
1938   struct value *v;
1939   int src,                      /* Index into the source area */
1940     targ,                       /* Index into the target area */
1941     srcBitsLeft,                /* Number of source bits left to move */
1942     nsrc, ntarg,                /* Number of source and target bytes */
1943     unusedLS,                   /* Number of bits in next significant
1944                                    byte of source that are unused */
1945     accumSize;                  /* Number of meaningful bits in accum */
1946   unsigned char *bytes;         /* First byte containing data to unpack */
1947   unsigned char *unpacked;
1948   unsigned long accum;          /* Staging area for bits being transferred */
1949   unsigned char sign;
1950   int len = (bit_size + bit_offset + HOST_CHAR_BIT - 1) / 8;
1951   /* Transmit bytes from least to most significant; delta is the direction
1952      the indices move.  */
1953   int delta = gdbarch_bits_big_endian (current_gdbarch) ? -1 : 1;
1954
1955   type = ada_check_typedef (type);
1956
1957   if (obj == NULL)
1958     {
1959       v = allocate_value (type);
1960       bytes = (unsigned char *) (valaddr + offset);
1961     }
1962   else if (VALUE_LVAL (obj) == lval_memory && value_lazy (obj))
1963     {
1964       v = value_at (type,
1965                     VALUE_ADDRESS (obj) + value_offset (obj) + offset);
1966       bytes = (unsigned char *) alloca (len);
1967       read_memory (VALUE_ADDRESS (v), bytes, len);
1968     }
1969   else
1970     {
1971       v = allocate_value (type);
1972       bytes = (unsigned char *) value_contents (obj) + offset;
1973     }
1974
1975   if (obj != NULL)
1976     {
1977       set_value_component_location (v, obj);
1978       VALUE_ADDRESS (v) += value_offset (obj) + offset;
1979       set_value_bitpos (v, bit_offset + value_bitpos (obj));
1980       set_value_bitsize (v, bit_size);
1981       if (value_bitpos (v) >= HOST_CHAR_BIT)
1982         {
1983           VALUE_ADDRESS (v) += 1;
1984           set_value_bitpos (v, value_bitpos (v) - HOST_CHAR_BIT);
1985         }
1986     }
1987   else
1988     set_value_bitsize (v, bit_size);
1989   unpacked = (unsigned char *) value_contents (v);
1990
1991   srcBitsLeft = bit_size;
1992   nsrc = len;
1993   ntarg = TYPE_LENGTH (type);
1994   sign = 0;
1995   if (bit_size == 0)
1996     {
1997       memset (unpacked, 0, TYPE_LENGTH (type));
1998       return v;
1999     }
2000   else if (gdbarch_bits_big_endian (current_gdbarch))
2001     {
2002       src = len - 1;
2003       if (has_negatives (type)
2004           && ((bytes[0] << bit_offset) & (1 << (HOST_CHAR_BIT - 1))))
2005         sign = ~0;
2006
2007       unusedLS =
2008         (HOST_CHAR_BIT - (bit_size + bit_offset) % HOST_CHAR_BIT)
2009         % HOST_CHAR_BIT;
2010
2011       switch (TYPE_CODE (type))
2012         {
2013         case TYPE_CODE_ARRAY:
2014         case TYPE_CODE_UNION:
2015         case TYPE_CODE_STRUCT:
2016           /* Non-scalar values must be aligned at a byte boundary...  */
2017           accumSize =
2018             (HOST_CHAR_BIT - bit_size % HOST_CHAR_BIT) % HOST_CHAR_BIT;
2019           /* ... And are placed at the beginning (most-significant) bytes
2020              of the target.  */
2021           targ = (bit_size + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT - 1;
2022           ntarg = targ + 1;
2023           break;
2024         default:
2025           accumSize = 0;
2026           targ = TYPE_LENGTH (type) - 1;
2027           break;
2028         }
2029     }
2030   else
2031     {
2032       int sign_bit_offset = (bit_size + bit_offset - 1) % 8;
2033
2034       src = targ = 0;
2035       unusedLS = bit_offset;
2036       accumSize = 0;
2037
2038       if (has_negatives (type) && (bytes[len - 1] & (1 << sign_bit_offset)))
2039         sign = ~0;
2040     }
2041
2042   accum = 0;
2043   while (nsrc > 0)
2044     {
2045       /* Mask for removing bits of the next source byte that are not
2046          part of the value.  */
2047       unsigned int unusedMSMask =
2048         (1 << (srcBitsLeft >= HOST_CHAR_BIT ? HOST_CHAR_BIT : srcBitsLeft)) -
2049         1;
2050       /* Sign-extend bits for this byte.  */
2051       unsigned int signMask = sign & ~unusedMSMask;
2052       accum |=
2053         (((bytes[src] >> unusedLS) & unusedMSMask) | signMask) << accumSize;
2054       accumSize += HOST_CHAR_BIT - unusedLS;
2055       if (accumSize >= HOST_CHAR_BIT)
2056         {
2057           unpacked[targ] = accum & ~(~0L << HOST_CHAR_BIT);
2058           accumSize -= HOST_CHAR_BIT;
2059           accum >>= HOST_CHAR_BIT;
2060           ntarg -= 1;
2061           targ += delta;
2062         }
2063       srcBitsLeft -= HOST_CHAR_BIT - unusedLS;
2064       unusedLS = 0;
2065       nsrc -= 1;
2066       src += delta;
2067     }
2068   while (ntarg > 0)
2069     {
2070       accum |= sign << accumSize;
2071       unpacked[targ] = accum & ~(~0L << HOST_CHAR_BIT);
2072       accumSize -= HOST_CHAR_BIT;
2073       accum >>= HOST_CHAR_BIT;
2074       ntarg -= 1;
2075       targ += delta;
2076     }
2077
2078   return v;
2079 }
2080
2081 /* Move N bits from SOURCE, starting at bit offset SRC_OFFSET to
2082    TARGET, starting at bit offset TARG_OFFSET.  SOURCE and TARGET must
2083    not overlap.  */
2084 static void
2085 move_bits (gdb_byte *target, int targ_offset, const gdb_byte *source,
2086            int src_offset, int n)
2087 {
2088   unsigned int accum, mask;
2089   int accum_bits, chunk_size;
2090
2091   target += targ_offset / HOST_CHAR_BIT;
2092   targ_offset %= HOST_CHAR_BIT;
2093   source += src_offset / HOST_CHAR_BIT;
2094   src_offset %= HOST_CHAR_BIT;
2095   if (gdbarch_bits_big_endian (current_gdbarch))
2096     {
2097       accum = (unsigned char) *source;
2098       source += 1;
2099       accum_bits = HOST_CHAR_BIT - src_offset;
2100
2101       while (n > 0)
2102         {
2103           int unused_right;
2104           accum = (accum << HOST_CHAR_BIT) + (unsigned char) *source;
2105           accum_bits += HOST_CHAR_BIT;
2106           source += 1;
2107           chunk_size = HOST_CHAR_BIT - targ_offset;
2108           if (chunk_size > n)
2109             chunk_size = n;
2110           unused_right = HOST_CHAR_BIT - (chunk_size + targ_offset);
2111           mask = ((1 << chunk_size) - 1) << unused_right;
2112           *target =
2113             (*target & ~mask)
2114             | ((accum >> (accum_bits - chunk_size - unused_right)) & mask);
2115           n -= chunk_size;
2116           accum_bits -= chunk_size;
2117           target += 1;
2118           targ_offset = 0;
2119         }
2120     }
2121   else
2122     {
2123       accum = (unsigned char) *source >> src_offset;
2124       source += 1;
2125       accum_bits = HOST_CHAR_BIT - src_offset;
2126
2127       while (n > 0)
2128         {
2129           accum = accum + ((unsigned char) *source << accum_bits);
2130           accum_bits += HOST_CHAR_BIT;
2131           source += 1;
2132           chunk_size = HOST_CHAR_BIT - targ_offset;
2133           if (chunk_size > n)
2134             chunk_size = n;
2135           mask = ((1 << chunk_size) - 1) << targ_offset;
2136           *target = (*target & ~mask) | ((accum << targ_offset) & mask);
2137           n -= chunk_size;
2138           accum_bits -= chunk_size;
2139           accum >>= chunk_size;
2140           target += 1;
2141           targ_offset = 0;
2142         }
2143     }
2144 }
2145
2146 /* Store the contents of FROMVAL into the location of TOVAL.
2147    Return a new value with the location of TOVAL and contents of
2148    FROMVAL.   Handles assignment into packed fields that have
2149    floating-point or non-scalar types.  */
2150
2151 static struct value *
2152 ada_value_assign (struct value *toval, struct value *fromval)
2153 {
2154   struct type *type = value_type (toval);
2155   int bits = value_bitsize (toval);
2156
2157   toval = ada_coerce_ref (toval);
2158   fromval = ada_coerce_ref (fromval);
2159
2160   if (ada_is_direct_array_type (value_type (toval)))
2161     toval = ada_coerce_to_simple_array (toval);
2162   if (ada_is_direct_array_type (value_type (fromval)))
2163     fromval = ada_coerce_to_simple_array (fromval);
2164
2165   if (!deprecated_value_modifiable (toval))
2166     error (_("Left operand of assignment is not a modifiable lvalue."));
2167
2168   if (VALUE_LVAL (toval) == lval_memory
2169       && bits > 0
2170       && (TYPE_CODE (type) == TYPE_CODE_FLT
2171           || TYPE_CODE (type) == TYPE_CODE_STRUCT))
2172     {
2173       int len = (value_bitpos (toval)
2174                  + bits + HOST_CHAR_BIT - 1) / HOST_CHAR_BIT;
2175       int from_size;
2176       char *buffer = (char *) alloca (len);
2177       struct value *val;
2178       CORE_ADDR to_addr = VALUE_ADDRESS (toval) + value_offset (toval);
2179
2180       if (TYPE_CODE (type) == TYPE_CODE_FLT)
2181         fromval = value_cast (type, fromval);
2182
2183       read_memory (to_addr, buffer, len);
2184       from_size = value_bitsize (fromval);
2185       if (from_size == 0)
2186         from_size = TYPE_LENGTH (value_type (fromval)) * TARGET_CHAR_BIT;
2187       if (gdbarch_bits_big_endian (current_gdbarch))
2188         move_bits (buffer, value_bitpos (toval),
2189                    value_contents (fromval), from_size - bits, bits);
2190       else
2191         move_bits (buffer, value_bitpos (toval), value_contents (fromval),
2192                    0, bits);
2193       write_memory (to_addr, buffer, len);
2194       if (deprecated_memory_changed_hook)
2195         deprecated_memory_changed_hook (to_addr, len);
2196       
2197       val = value_copy (toval);
2198       memcpy (value_contents_raw (val), value_contents (fromval),
2199               TYPE_LENGTH (type));
2200       deprecated_set_value_type (val, type);
2201
2202       return val;
2203     }
2204
2205   return value_assign (toval, fromval);
2206 }
2207
2208
2209 /* Given that COMPONENT is a memory lvalue that is part of the lvalue 
2210  * CONTAINER, assign the contents of VAL to COMPONENTS's place in 
2211  * CONTAINER.  Modifies the VALUE_CONTENTS of CONTAINER only, not 
2212  * COMPONENT, and not the inferior's memory.  The current contents 
2213  * of COMPONENT are ignored.  */
2214 static void
2215 value_assign_to_component (struct value *container, struct value *component,
2216                            struct value *val)
2217 {
2218   LONGEST offset_in_container =
2219     (LONGEST)  (VALUE_ADDRESS (component) + value_offset (component)
2220                 - VALUE_ADDRESS (container) - value_offset (container));
2221   int bit_offset_in_container = 
2222     value_bitpos (component) - value_bitpos (container);
2223   int bits;
2224   
2225   val = value_cast (value_type (component), val);
2226
2227   if (value_bitsize (component) == 0)
2228     bits = TARGET_CHAR_BIT * TYPE_LENGTH (value_type (component));
2229   else
2230     bits = value_bitsize (component);
2231
2232   if (gdbarch_bits_big_endian (current_gdbarch))
2233     move_bits (value_contents_writeable (container) + offset_in_container, 
2234                value_bitpos (container) + bit_offset_in_container,
2235                value_contents (val),
2236                TYPE_LENGTH (value_type (component)) * TARGET_CHAR_BIT - bits,
2237                bits);
2238   else
2239     move_bits (value_contents_writeable (container) + offset_in_container, 
2240                value_bitpos (container) + bit_offset_in_container,
2241                value_contents (val), 0, bits);
2242 }              
2243                         
2244 /* The value of the element of array ARR at the ARITY indices given in IND.
2245    ARR may be either a simple array, GNAT array descriptor, or pointer
2246    thereto.  */
2247
2248 struct value *
2249 ada_value_subscript (struct value *arr, int arity, struct value **ind)
2250 {
2251   int k;
2252   struct value *elt;
2253   struct type *elt_type;
2254
2255   elt = ada_coerce_to_simple_array (arr);
2256
2257   elt_type = ada_check_typedef (value_type (elt));
2258   if (TYPE_CODE (elt_type) == TYPE_CODE_ARRAY
2259       && TYPE_FIELD_BITSIZE (elt_type, 0) > 0)
2260     return value_subscript_packed (elt, arity, ind);
2261
2262   for (k = 0; k < arity; k += 1)
2263     {
2264       if (TYPE_CODE (elt_type) != TYPE_CODE_ARRAY)
2265         error (_("too many subscripts (%d expected)"), k);
2266       elt = value_subscript (elt, value_pos_atr (builtin_type_int32, ind[k]));
2267     }
2268   return elt;
2269 }
2270
2271 /* Assuming ARR is a pointer to a standard GDB array of type TYPE, the
2272    value of the element of *ARR at the ARITY indices given in
2273    IND.  Does not read the entire array into memory.  */
2274
2275 static struct value *
2276 ada_value_ptr_subscript (struct value *arr, struct type *type, int arity,
2277                          struct value **ind)
2278 {
2279   int k;
2280
2281   for (k = 0; k < arity; k += 1)
2282     {
2283       LONGEST lwb, upb;
2284       struct value *idx;
2285
2286       if (TYPE_CODE (type) != TYPE_CODE_ARRAY)
2287         error (_("too many subscripts (%d expected)"), k);
2288       arr = value_cast (lookup_pointer_type (TYPE_TARGET_TYPE (type)),
2289                         value_copy (arr));
2290       get_discrete_bounds (TYPE_INDEX_TYPE (type), &lwb, &upb);
2291       idx = value_pos_atr (builtin_type_int32, ind[k]);
2292       if (lwb != 0)
2293         idx = value_binop (idx, value_from_longest (value_type (idx), lwb),
2294                            BINOP_SUB);
2295
2296       arr = value_ptradd (arr, idx);
2297       type = TYPE_TARGET_TYPE (type);
2298     }
2299
2300   return value_ind (arr);
2301 }
2302
2303 /* Given that ARRAY_PTR is a pointer or reference to an array of type TYPE (the
2304    actual type of ARRAY_PTR is ignored), returns the Ada slice of HIGH-LOW+1
2305    elements starting at index LOW.  The lower bound of this array is LOW, as
2306    per Ada rules. */
2307 static struct value *
2308 ada_value_slice_from_ptr (struct value *array_ptr, struct type *type,
2309                           int low, int high)
2310 {
2311   CORE_ADDR base = value_as_address (array_ptr)
2312     + ((low - TYPE_LOW_BOUND (TYPE_INDEX_TYPE (type)))
2313        * TYPE_LENGTH (TYPE_TARGET_TYPE (type)));
2314   struct type *index_type =
2315     create_range_type (NULL, TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type)),
2316                        low, high);
2317   struct type *slice_type =
2318     create_array_type (NULL, TYPE_TARGET_TYPE (type), index_type);
2319   return value_at_lazy (slice_type, base);
2320 }
2321
2322
2323 static struct value *
2324 ada_value_slice (struct value *array, int low, int high)
2325 {
2326   struct type *type = value_type (array);
2327   struct type *index_type =
2328     create_range_type (NULL, TYPE_INDEX_TYPE (type), low, high);
2329   struct type *slice_type =
2330     create_array_type (NULL, TYPE_TARGET_TYPE (type), index_type);
2331   return value_cast (slice_type, value_slice (array, low, high - low + 1));
2332 }
2333
2334 /* If type is a record type in the form of a standard GNAT array
2335    descriptor, returns the number of dimensions for type.  If arr is a
2336    simple array, returns the number of "array of"s that prefix its
2337    type designation.  Otherwise, returns 0.  */
2338
2339 int
2340 ada_array_arity (struct type *type)
2341 {
2342   int arity;
2343
2344   if (type == NULL)
2345     return 0;
2346
2347   type = desc_base_type (type);
2348
2349   arity = 0;
2350   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
2351     return desc_arity (desc_bounds_type (type));
2352   else
2353     while (TYPE_CODE (type) == TYPE_CODE_ARRAY)
2354       {
2355         arity += 1;
2356         type = ada_check_typedef (TYPE_TARGET_TYPE (type));
2357       }
2358
2359   return arity;
2360 }
2361
2362 /* If TYPE is a record type in the form of a standard GNAT array
2363    descriptor or a simple array type, returns the element type for
2364    TYPE after indexing by NINDICES indices, or by all indices if
2365    NINDICES is -1.  Otherwise, returns NULL.  */
2366
2367 struct type *
2368 ada_array_element_type (struct type *type, int nindices)
2369 {
2370   type = desc_base_type (type);
2371
2372   if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
2373     {
2374       int k;
2375       struct type *p_array_type;
2376
2377       p_array_type = desc_data_type (type);
2378
2379       k = ada_array_arity (type);
2380       if (k == 0)
2381         return NULL;
2382
2383       /* Initially p_array_type = elt_type(*)[]...(k times)...[].  */
2384       if (nindices >= 0 && k > nindices)
2385         k = nindices;
2386       p_array_type = TYPE_TARGET_TYPE (p_array_type);
2387       while (k > 0 && p_array_type != NULL)
2388         {
2389           p_array_type = ada_check_typedef (TYPE_TARGET_TYPE (p_array_type));
2390           k -= 1;
2391         }
2392       return p_array_type;
2393     }
2394   else if (TYPE_CODE (type) == TYPE_CODE_ARRAY)
2395     {
2396       while (nindices != 0 && TYPE_CODE (type) == TYPE_CODE_ARRAY)
2397         {
2398           type = TYPE_TARGET_TYPE (type);
2399           nindices -= 1;
2400         }
2401       return type;
2402     }
2403
2404   return NULL;
2405 }
2406
2407 /* The type of nth index in arrays of given type (n numbering from 1).
2408    Does not examine memory.  */
2409
2410 struct type *
2411 ada_index_type (struct type *type, int n)
2412 {
2413   struct type *result_type;
2414
2415   type = desc_base_type (type);
2416
2417   if (n > ada_array_arity (type))
2418     return NULL;
2419
2420   if (ada_is_simple_array_type (type))
2421     {
2422       int i;
2423
2424       for (i = 1; i < n; i += 1)
2425         type = TYPE_TARGET_TYPE (type);
2426       result_type = TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (type));
2427       /* FIXME: The stabs type r(0,0);bound;bound in an array type
2428          has a target type of TYPE_CODE_UNDEF.  We compensate here, but
2429          perhaps stabsread.c would make more sense.  */
2430       if (result_type == NULL || TYPE_CODE (result_type) == TYPE_CODE_UNDEF)
2431         result_type = builtin_type_int32;
2432
2433       return result_type;
2434     }
2435   else
2436     return desc_index_type (desc_bounds_type (type), n);
2437 }
2438
2439 /* Given that arr is an array type, returns the lower bound of the
2440    Nth index (numbering from 1) if WHICH is 0, and the upper bound if
2441    WHICH is 1.  This returns bounds 0 .. -1 if ARR_TYPE is an
2442    array-descriptor type.  If TYPEP is non-null, *TYPEP is set to the
2443    bounds type.  It works for other arrays with bounds supplied by
2444    run-time quantities other than discriminants.  */
2445
2446 static LONGEST
2447 ada_array_bound_from_type (struct type * arr_type, int n, int which,
2448                            struct type ** typep)
2449 {
2450   struct type *type, *index_type_desc, *index_type;
2451   LONGEST retval;
2452
2453   gdb_assert (which == 0 || which == 1);
2454
2455   if (ada_is_packed_array_type (arr_type))
2456     arr_type = decode_packed_array_type (arr_type);
2457
2458   if (arr_type == NULL || !ada_is_simple_array_type (arr_type))
2459     {
2460       if (typep != NULL)
2461         *typep = builtin_type_int32;
2462       return (LONGEST) - which;
2463     }
2464
2465   if (TYPE_CODE (arr_type) == TYPE_CODE_PTR)
2466     type = TYPE_TARGET_TYPE (arr_type);
2467   else
2468     type = arr_type;
2469
2470   index_type_desc = ada_find_parallel_type (type, "___XA");
2471   if (index_type_desc != NULL)
2472     index_type = to_fixed_range_type (TYPE_FIELD_NAME (index_type_desc, n - 1),
2473                                       NULL, TYPE_OBJFILE (arr_type));
2474   else
2475     {
2476       while (n > 1)
2477         {
2478           type = TYPE_TARGET_TYPE (type);
2479           n -= 1;
2480         }
2481
2482       index_type = TYPE_INDEX_TYPE (type);
2483     }
2484
2485   switch (TYPE_CODE (index_type))
2486     {
2487     case TYPE_CODE_RANGE:
2488       retval = which == 0 ? TYPE_LOW_BOUND (index_type)
2489                           : TYPE_HIGH_BOUND (index_type);
2490       break;
2491     case TYPE_CODE_ENUM:
2492       retval = which == 0 ? TYPE_FIELD_BITPOS (index_type, 0)
2493                           : TYPE_FIELD_BITPOS (index_type,
2494                                                TYPE_NFIELDS (index_type) - 1);
2495       break;
2496     default:
2497       internal_error (__FILE__, __LINE__, _("invalid type code of index type"));
2498     }
2499
2500   if (typep != NULL)
2501     *typep = index_type;
2502
2503   return retval;
2504 }
2505
2506 /* Given that arr is an array value, returns the lower bound of the
2507    nth index (numbering from 1) if WHICH is 0, and the upper bound if
2508    WHICH is 1.  This routine will also work for arrays with bounds
2509    supplied by run-time quantities other than discriminants.  */
2510
2511 struct value *
2512 ada_array_bound (struct value *arr, int n, int which)
2513 {
2514   struct type *arr_type = value_type (arr);
2515
2516   if (ada_is_packed_array_type (arr_type))
2517     return ada_array_bound (decode_packed_array (arr), n, which);
2518   else if (ada_is_simple_array_type (arr_type))
2519     {
2520       struct type *type;
2521       LONGEST v = ada_array_bound_from_type (arr_type, n, which, &type);
2522       return value_from_longest (type, v);
2523     }
2524   else
2525     return desc_one_bound (desc_bounds (arr), n, which);
2526 }
2527
2528 /* Given that arr is an array value, returns the length of the
2529    nth index.  This routine will also work for arrays with bounds
2530    supplied by run-time quantities other than discriminants.
2531    Does not work for arrays indexed by enumeration types with representation
2532    clauses at the moment.  */
2533
2534 static struct value *
2535 ada_array_length (struct value *arr, int n)
2536 {
2537   struct type *arr_type = ada_check_typedef (value_type (arr));
2538
2539   if (ada_is_packed_array_type (arr_type))
2540     return ada_array_length (decode_packed_array (arr), n);
2541
2542   if (ada_is_simple_array_type (arr_type))
2543     {
2544       struct type *type;
2545       LONGEST v =
2546         ada_array_bound_from_type (arr_type, n, 1, &type) -
2547         ada_array_bound_from_type (arr_type, n, 0, NULL) + 1;
2548       return value_from_longest (type, v);
2549     }
2550   else
2551     return
2552       value_from_longest (builtin_type_int32,
2553                           value_as_long (desc_one_bound (desc_bounds (arr),
2554                                                          n, 1))
2555                           - value_as_long (desc_one_bound (desc_bounds (arr),
2556                                                            n, 0)) + 1);
2557 }
2558
2559 /* An empty array whose type is that of ARR_TYPE (an array type),
2560    with bounds LOW to LOW-1.  */
2561
2562 static struct value *
2563 empty_array (struct type *arr_type, int low)
2564 {
2565   struct type *index_type =
2566     create_range_type (NULL, TYPE_TARGET_TYPE (TYPE_INDEX_TYPE (arr_type)),
2567                        low, low - 1);
2568   struct type *elt_type = ada_array_element_type (arr_type, 1);
2569   return allocate_value (create_array_type (NULL, elt_type, index_type));
2570 }
2571 \f
2572
2573                                 /* Name resolution */
2574
2575 /* The "decoded" name for the user-definable Ada operator corresponding
2576    to OP.  */
2577
2578 static const char *
2579 ada_decoded_op_name (enum exp_opcode op)
2580 {
2581   int i;
2582
2583   for (i = 0; ada_opname_table[i].encoded != NULL; i += 1)
2584     {
2585       if (ada_opname_table[i].op == op)
2586         return ada_opname_table[i].decoded;
2587     }
2588   error (_("Could not find operator name for opcode"));
2589 }
2590
2591
2592 /* Same as evaluate_type (*EXP), but resolves ambiguous symbol
2593    references (marked by OP_VAR_VALUE nodes in which the symbol has an
2594    undefined namespace) and converts operators that are
2595    user-defined into appropriate function calls.  If CONTEXT_TYPE is
2596    non-null, it provides a preferred result type [at the moment, only
2597    type void has any effect---causing procedures to be preferred over
2598    functions in calls].  A null CONTEXT_TYPE indicates that a non-void
2599    return type is preferred.  May change (expand) *EXP.  */
2600
2601 static void
2602 resolve (struct expression **expp, int void_context_p)
2603 {
2604   int pc;
2605   pc = 0;
2606   resolve_subexp (expp, &pc, 1, void_context_p ? builtin_type_void : NULL);
2607 }
2608
2609 /* Resolve the operator of the subexpression beginning at
2610    position *POS of *EXPP.  "Resolving" consists of replacing
2611    the symbols that have undefined namespaces in OP_VAR_VALUE nodes
2612    with their resolutions, replacing built-in operators with
2613    function calls to user-defined operators, where appropriate, and,
2614    when DEPROCEDURE_P is non-zero, converting function-valued variables
2615    into parameterless calls.  May expand *EXPP.  The CONTEXT_TYPE functions
2616    are as in ada_resolve, above.  */
2617
2618 static struct value *
2619 resolve_subexp (struct expression **expp, int *pos, int deprocedure_p,
2620                 struct type *context_type)
2621 {
2622   int pc = *pos;
2623   int i;
2624   struct expression *exp;       /* Convenience: == *expp.  */
2625   enum exp_opcode op = (*expp)->elts[pc].opcode;
2626   struct value **argvec;        /* Vector of operand types (alloca'ed).  */
2627   int nargs;                    /* Number of operands.  */
2628   int oplen;
2629
2630   argvec = NULL;
2631   nargs = 0;
2632   exp = *expp;
2633
2634   /* Pass one: resolve operands, saving their types and updating *pos,
2635      if needed.  */
2636   switch (op)
2637     {
2638     case OP_FUNCALL:
2639       if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
2640           && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
2641         *pos += 7;
2642       else
2643         {
2644           *pos += 3;
2645           resolve_subexp (expp, pos, 0, NULL);
2646         }
2647       nargs = longest_to_int (exp->elts[pc + 1].longconst);
2648       break;
2649
2650     case UNOP_ADDR:
2651       *pos += 1;
2652       resolve_subexp (expp, pos, 0, NULL);
2653       break;
2654
2655     case UNOP_QUAL:
2656       *pos += 3;
2657       resolve_subexp (expp, pos, 1, exp->elts[pc + 1].type);
2658       break;
2659
2660     case OP_ATR_MODULUS:
2661     case OP_ATR_SIZE:
2662     case OP_ATR_TAG:
2663     case OP_ATR_FIRST:
2664     case OP_ATR_LAST:
2665     case OP_ATR_LENGTH:
2666     case OP_ATR_POS:
2667     case OP_ATR_VAL:
2668     case OP_ATR_MIN:
2669     case OP_ATR_MAX:
2670     case TERNOP_IN_RANGE:
2671     case BINOP_IN_BOUNDS:
2672     case UNOP_IN_RANGE:
2673     case OP_AGGREGATE:
2674     case OP_OTHERS:
2675     case OP_CHOICES:
2676     case OP_POSITIONAL:
2677     case OP_DISCRETE_RANGE:
2678     case OP_NAME:
2679       ada_forward_operator_length (exp, pc, &oplen, &nargs);
2680       *pos += oplen;
2681       break;
2682
2683     case BINOP_ASSIGN:
2684       {
2685         struct value *arg1;
2686
2687         *pos += 1;
2688         arg1 = resolve_subexp (expp, pos, 0, NULL);
2689         if (arg1 == NULL)
2690           resolve_subexp (expp, pos, 1, NULL);
2691         else
2692           resolve_subexp (expp, pos, 1, value_type (arg1));
2693         break;
2694       }
2695
2696     case UNOP_CAST:
2697       *pos += 3;
2698       nargs = 1;
2699       break;
2700
2701     case BINOP_ADD:
2702     case BINOP_SUB:
2703     case BINOP_MUL:
2704     case BINOP_DIV:
2705     case BINOP_REM:
2706     case BINOP_MOD:
2707     case BINOP_EXP:
2708     case BINOP_CONCAT:
2709     case BINOP_LOGICAL_AND:
2710     case BINOP_LOGICAL_OR:
2711     case BINOP_BITWISE_AND:
2712     case BINOP_BITWISE_IOR:
2713     case BINOP_BITWISE_XOR:
2714
2715     case BINOP_EQUAL:
2716     case BINOP_NOTEQUAL:
2717     case BINOP_LESS:
2718     case BINOP_GTR:
2719     case BINOP_LEQ:
2720     case BINOP_GEQ:
2721
2722     case BINOP_REPEAT:
2723     case BINOP_SUBSCRIPT:
2724     case BINOP_COMMA:
2725       *pos += 1;
2726       nargs = 2;
2727       break;
2728
2729     case UNOP_NEG:
2730     case UNOP_PLUS:
2731     case UNOP_LOGICAL_NOT:
2732     case UNOP_ABS:
2733     case UNOP_IND:
2734       *pos += 1;
2735       nargs = 1;
2736       break;
2737
2738     case OP_LONG:
2739     case OP_DOUBLE:
2740     case OP_VAR_VALUE:
2741       *pos += 4;
2742       break;
2743
2744     case OP_TYPE:
2745     case OP_BOOL:
2746     case OP_LAST:
2747     case OP_INTERNALVAR:
2748       *pos += 3;
2749       break;
2750
2751     case UNOP_MEMVAL:
2752       *pos += 3;
2753       nargs = 1;
2754       break;
2755
2756     case OP_REGISTER:
2757       *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
2758       break;
2759
2760     case STRUCTOP_STRUCT:
2761       *pos += 4 + BYTES_TO_EXP_ELEM (exp->elts[pc + 1].longconst + 1);
2762       nargs = 1;
2763       break;
2764
2765     case TERNOP_SLICE:
2766       *pos += 1;
2767       nargs = 3;
2768       break;
2769
2770     case OP_STRING:
2771       break;
2772
2773     default:
2774       error (_("Unexpected operator during name resolution"));
2775     }
2776
2777   argvec = (struct value * *) alloca (sizeof (struct value *) * (nargs + 1));
2778   for (i = 0; i < nargs; i += 1)
2779     argvec[i] = resolve_subexp (expp, pos, 1, NULL);
2780   argvec[i] = NULL;
2781   exp = *expp;
2782
2783   /* Pass two: perform any resolution on principal operator.  */
2784   switch (op)
2785     {
2786     default:
2787       break;
2788
2789     case OP_VAR_VALUE:
2790       if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
2791         {
2792           struct ada_symbol_info *candidates;
2793           int n_candidates;
2794
2795           n_candidates =
2796             ada_lookup_symbol_list (SYMBOL_LINKAGE_NAME
2797                                     (exp->elts[pc + 2].symbol),
2798                                     exp->elts[pc + 1].block, VAR_DOMAIN,
2799                                     &candidates);
2800
2801           if (n_candidates > 1)
2802             {
2803               /* Types tend to get re-introduced locally, so if there
2804                  are any local symbols that are not types, first filter
2805                  out all types.  */
2806               int j;
2807               for (j = 0; j < n_candidates; j += 1)
2808                 switch (SYMBOL_CLASS (candidates[j].sym))
2809                   {
2810                   case LOC_REGISTER:
2811                   case LOC_ARG:
2812                   case LOC_REF_ARG:
2813                   case LOC_REGPARM_ADDR:
2814                   case LOC_LOCAL:
2815                   case LOC_COMPUTED:
2816                     goto FoundNonType;
2817                   default:
2818                     break;
2819                   }
2820             FoundNonType:
2821               if (j < n_candidates)
2822                 {
2823                   j = 0;
2824                   while (j < n_candidates)
2825                     {
2826                       if (SYMBOL_CLASS (candidates[j].sym) == LOC_TYPEDEF)
2827                         {
2828                           candidates[j] = candidates[n_candidates - 1];
2829                           n_candidates -= 1;
2830                         }
2831                       else
2832                         j += 1;
2833                     }
2834                 }
2835             }
2836
2837           if (n_candidates == 0)
2838             error (_("No definition found for %s"),
2839                    SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
2840           else if (n_candidates == 1)
2841             i = 0;
2842           else if (deprocedure_p
2843                    && !is_nonfunction (candidates, n_candidates))
2844             {
2845               i = ada_resolve_function
2846                 (candidates, n_candidates, NULL, 0,
2847                  SYMBOL_LINKAGE_NAME (exp->elts[pc + 2].symbol),
2848                  context_type);
2849               if (i < 0)
2850                 error (_("Could not find a match for %s"),
2851                        SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
2852             }
2853           else
2854             {
2855               printf_filtered (_("Multiple matches for %s\n"),
2856                                SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
2857               user_select_syms (candidates, n_candidates, 1);
2858               i = 0;
2859             }
2860
2861           exp->elts[pc + 1].block = candidates[i].block;
2862           exp->elts[pc + 2].symbol = candidates[i].sym;
2863           if (innermost_block == NULL
2864               || contained_in (candidates[i].block, innermost_block))
2865             innermost_block = candidates[i].block;
2866         }
2867
2868       if (deprocedure_p
2869           && (TYPE_CODE (SYMBOL_TYPE (exp->elts[pc + 2].symbol))
2870               == TYPE_CODE_FUNC))
2871         {
2872           replace_operator_with_call (expp, pc, 0, 0,
2873                                       exp->elts[pc + 2].symbol,
2874                                       exp->elts[pc + 1].block);
2875           exp = *expp;
2876         }
2877       break;
2878
2879     case OP_FUNCALL:
2880       {
2881         if (exp->elts[pc + 3].opcode == OP_VAR_VALUE
2882             && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
2883           {
2884             struct ada_symbol_info *candidates;
2885             int n_candidates;
2886
2887             n_candidates =
2888               ada_lookup_symbol_list (SYMBOL_LINKAGE_NAME
2889                                       (exp->elts[pc + 5].symbol),
2890                                       exp->elts[pc + 4].block, VAR_DOMAIN,
2891                                       &candidates);
2892             if (n_candidates == 1)
2893               i = 0;
2894             else
2895               {
2896                 i = ada_resolve_function
2897                   (candidates, n_candidates,
2898                    argvec, nargs,
2899                    SYMBOL_LINKAGE_NAME (exp->elts[pc + 5].symbol),
2900                    context_type);
2901                 if (i < 0)
2902                   error (_("Could not find a match for %s"),
2903                          SYMBOL_PRINT_NAME (exp->elts[pc + 5].symbol));
2904               }
2905
2906             exp->elts[pc + 4].block = candidates[i].block;
2907             exp->elts[pc + 5].symbol = candidates[i].sym;
2908             if (innermost_block == NULL
2909                 || contained_in (candidates[i].block, innermost_block))
2910               innermost_block = candidates[i].block;
2911           }
2912       }
2913       break;
2914     case BINOP_ADD:
2915     case BINOP_SUB:
2916     case BINOP_MUL:
2917     case BINOP_DIV:
2918     case BINOP_REM:
2919     case BINOP_MOD:
2920     case BINOP_CONCAT:
2921     case BINOP_BITWISE_AND:
2922     case BINOP_BITWISE_IOR:
2923     case BINOP_BITWISE_XOR:
2924     case BINOP_EQUAL:
2925     case BINOP_NOTEQUAL:
2926     case BINOP_LESS:
2927     case BINOP_GTR:
2928     case BINOP_LEQ:
2929     case BINOP_GEQ:
2930     case BINOP_EXP:
2931     case UNOP_NEG:
2932     case UNOP_PLUS:
2933     case UNOP_LOGICAL_NOT:
2934     case UNOP_ABS:
2935       if (possible_user_operator_p (op, argvec))
2936         {
2937           struct ada_symbol_info *candidates;
2938           int n_candidates;
2939
2940           n_candidates =
2941             ada_lookup_symbol_list (ada_encode (ada_decoded_op_name (op)),
2942                                     (struct block *) NULL, VAR_DOMAIN,
2943                                     &candidates);
2944           i = ada_resolve_function (candidates, n_candidates, argvec, nargs,
2945                                     ada_decoded_op_name (op), NULL);
2946           if (i < 0)
2947             break;
2948
2949           replace_operator_with_call (expp, pc, nargs, 1,
2950                                       candidates[i].sym, candidates[i].block);
2951           exp = *expp;
2952         }
2953       break;
2954
2955     case OP_TYPE:
2956     case OP_REGISTER:
2957       return NULL;
2958     }
2959
2960   *pos = pc;
2961   return evaluate_subexp_type (exp, pos);
2962 }
2963
2964 /* Return non-zero if formal type FTYPE matches actual type ATYPE.  If
2965    MAY_DEREF is non-zero, the formal may be a pointer and the actual
2966    a non-pointer.   A type of 'void' (which is never a valid expression type)
2967    by convention matches anything. */
2968 /* The term "match" here is rather loose.  The match is heuristic and
2969    liberal.  FIXME: TOO liberal, in fact.  */
2970
2971 static int
2972 ada_type_match (struct type *ftype, struct type *atype, int may_deref)
2973 {
2974   ftype = ada_check_typedef (ftype);
2975   atype = ada_check_typedef (atype);
2976
2977   if (TYPE_CODE (ftype) == TYPE_CODE_REF)
2978     ftype = TYPE_TARGET_TYPE (ftype);
2979   if (TYPE_CODE (atype) == TYPE_CODE_REF)
2980     atype = TYPE_TARGET_TYPE (atype);
2981
2982   if (TYPE_CODE (ftype) == TYPE_CODE_VOID
2983       || TYPE_CODE (atype) == TYPE_CODE_VOID)
2984     return 1;
2985
2986   switch (TYPE_CODE (ftype))
2987     {
2988     default:
2989       return 1;
2990     case TYPE_CODE_PTR:
2991       if (TYPE_CODE (atype) == TYPE_CODE_PTR)
2992         return ada_type_match (TYPE_TARGET_TYPE (ftype),
2993                                TYPE_TARGET_TYPE (atype), 0);
2994       else
2995         return (may_deref
2996                 && ada_type_match (TYPE_TARGET_TYPE (ftype), atype, 0));
2997     case TYPE_CODE_INT:
2998     case TYPE_CODE_ENUM:
2999     case TYPE_CODE_RANGE:
3000       switch (TYPE_CODE (atype))
3001         {
3002         case TYPE_CODE_INT:
3003         case TYPE_CODE_ENUM:
3004         case TYPE_CODE_RANGE:
3005           return 1;
3006         default:
3007           return 0;
3008         }
3009
3010     case TYPE_CODE_ARRAY:
3011       return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
3012               || ada_is_array_descriptor_type (atype));
3013
3014     case TYPE_CODE_STRUCT:
3015       if (ada_is_array_descriptor_type (ftype))
3016         return (TYPE_CODE (atype) == TYPE_CODE_ARRAY
3017                 || ada_is_array_descriptor_type (atype));
3018       else
3019         return (TYPE_CODE (atype) == TYPE_CODE_STRUCT
3020                 && !ada_is_array_descriptor_type (atype));
3021
3022     case TYPE_CODE_UNION:
3023     case TYPE_CODE_FLT:
3024       return (TYPE_CODE (atype) == TYPE_CODE (ftype));
3025     }
3026 }
3027
3028 /* Return non-zero if the formals of FUNC "sufficiently match" the
3029    vector of actual argument types ACTUALS of size N_ACTUALS.  FUNC
3030    may also be an enumeral, in which case it is treated as a 0-
3031    argument function.  */
3032
3033 static int
3034 ada_args_match (struct symbol *func, struct value **actuals, int n_actuals)
3035 {
3036   int i;
3037   struct type *func_type = SYMBOL_TYPE (func);
3038
3039   if (SYMBOL_CLASS (func) == LOC_CONST
3040       && TYPE_CODE (func_type) == TYPE_CODE_ENUM)
3041     return (n_actuals == 0);
3042   else if (func_type == NULL || TYPE_CODE (func_type) != TYPE_CODE_FUNC)
3043     return 0;
3044
3045   if (TYPE_NFIELDS (func_type) != n_actuals)
3046     return 0;
3047
3048   for (i = 0; i < n_actuals; i += 1)
3049     {
3050       if (actuals[i] == NULL)
3051         return 0;
3052       else
3053         {
3054           struct type *ftype = ada_check_typedef (TYPE_FIELD_TYPE (func_type, i));
3055           struct type *atype = ada_check_typedef (value_type (actuals[i]));
3056
3057           if (!ada_type_match (ftype, atype, 1))
3058             return 0;
3059         }
3060     }
3061   return 1;
3062 }
3063
3064 /* False iff function type FUNC_TYPE definitely does not produce a value
3065    compatible with type CONTEXT_TYPE.  Conservatively returns 1 if
3066    FUNC_TYPE is not a valid function type with a non-null return type
3067    or an enumerated type.  A null CONTEXT_TYPE indicates any non-void type.  */
3068
3069 static int
3070 return_match (struct type *func_type, struct type *context_type)
3071 {
3072   struct type *return_type;
3073
3074   if (func_type == NULL)
3075     return 1;
3076
3077   if (TYPE_CODE (func_type) == TYPE_CODE_FUNC)
3078     return_type = base_type (TYPE_TARGET_TYPE (func_type));
3079   else
3080     return_type = base_type (func_type);
3081   if (return_type == NULL)
3082     return 1;
3083
3084   context_type = base_type (context_type);
3085
3086   if (TYPE_CODE (return_type) == TYPE_CODE_ENUM)
3087     return context_type == NULL || return_type == context_type;
3088   else if (context_type == NULL)
3089     return TYPE_CODE (return_type) != TYPE_CODE_VOID;
3090   else
3091     return TYPE_CODE (return_type) == TYPE_CODE (context_type);
3092 }
3093
3094
3095 /* Returns the index in SYMS[0..NSYMS-1] that contains  the symbol for the
3096    function (if any) that matches the types of the NARGS arguments in
3097    ARGS.  If CONTEXT_TYPE is non-null and there is at least one match
3098    that returns that type, then eliminate matches that don't.  If
3099    CONTEXT_TYPE is void and there is at least one match that does not
3100    return void, eliminate all matches that do.
3101
3102    Asks the user if there is more than one match remaining.  Returns -1
3103    if there is no such symbol or none is selected.  NAME is used
3104    solely for messages.  May re-arrange and modify SYMS in
3105    the process; the index returned is for the modified vector.  */
3106
3107 static int
3108 ada_resolve_function (struct ada_symbol_info syms[],
3109                       int nsyms, struct value **args, int nargs,
3110                       const char *name, struct type *context_type)
3111 {
3112   int k;
3113   int m;                        /* Number of hits */
3114   struct type *fallback;
3115   struct type *return_type;
3116
3117   return_type = context_type;
3118   if (context_type == NULL)
3119     fallback = builtin_type_void;
3120   else
3121     fallback = NULL;
3122
3123   m = 0;
3124   while (1)
3125     {
3126       for (k = 0; k < nsyms; k += 1)
3127         {
3128           struct type *type = ada_check_typedef (SYMBOL_TYPE (syms[k].sym));
3129
3130           if (ada_args_match (syms[k].sym, args, nargs)
3131               && return_match (type, return_type))
3132             {
3133               syms[m] = syms[k];
3134               m += 1;
3135             }
3136         }
3137       if (m > 0 || return_type == fallback)
3138         break;
3139       else
3140         return_type = fallback;
3141     }
3142
3143   if (m == 0)
3144     return -1;
3145   else if (m > 1)
3146     {
3147       printf_filtered (_("Multiple matches for %s\n"), name);
3148       user_select_syms (syms, m, 1);
3149       return 0;
3150     }
3151   return 0;
3152 }
3153
3154 /* Returns true (non-zero) iff decoded name N0 should appear before N1
3155    in a listing of choices during disambiguation (see sort_choices, below).
3156    The idea is that overloadings of a subprogram name from the
3157    same package should sort in their source order.  We settle for ordering
3158    such symbols by their trailing number (__N  or $N).  */
3159
3160 static int
3161 encoded_ordered_before (char *N0, char *N1)
3162 {
3163   if (N1 == NULL)
3164     return 0;
3165   else if (N0 == NULL)
3166     return 1;
3167   else
3168     {
3169       int k0, k1;
3170       for (k0 = strlen (N0) - 1; k0 > 0 && isdigit (N0[k0]); k0 -= 1)
3171         ;
3172       for (k1 = strlen (N1) - 1; k1 > 0 && isdigit (N1[k1]); k1 -= 1)
3173         ;
3174       if ((N0[k0] == '_' || N0[k0] == '$') && N0[k0 + 1] != '\000'
3175           && (N1[k1] == '_' || N1[k1] == '$') && N1[k1 + 1] != '\000')
3176         {
3177           int n0, n1;
3178           n0 = k0;
3179           while (N0[n0] == '_' && n0 > 0 && N0[n0 - 1] == '_')
3180             n0 -= 1;
3181           n1 = k1;
3182           while (N1[n1] == '_' && n1 > 0 && N1[n1 - 1] == '_')
3183             n1 -= 1;
3184           if (n0 == n1 && strncmp (N0, N1, n0) == 0)
3185             return (atoi (N0 + k0 + 1) < atoi (N1 + k1 + 1));
3186         }
3187       return (strcmp (N0, N1) < 0);
3188     }
3189 }
3190
3191 /* Sort SYMS[0..NSYMS-1] to put the choices in a canonical order by the
3192    encoded names.  */
3193
3194 static void
3195 sort_choices (struct ada_symbol_info syms[], int nsyms)
3196 {
3197   int i;
3198   for (i = 1; i < nsyms; i += 1)
3199     {
3200       struct ada_symbol_info sym = syms[i];
3201       int j;
3202
3203       for (j = i - 1; j >= 0; j -= 1)
3204         {
3205           if (encoded_ordered_before (SYMBOL_LINKAGE_NAME (syms[j].sym),
3206                                       SYMBOL_LINKAGE_NAME (sym.sym)))
3207             break;
3208           syms[j + 1] = syms[j];
3209         }
3210       syms[j + 1] = sym;
3211     }
3212 }
3213
3214 /* Given a list of NSYMS symbols in SYMS, select up to MAX_RESULTS>0 
3215    by asking the user (if necessary), returning the number selected, 
3216    and setting the first elements of SYMS items.  Error if no symbols
3217    selected.  */
3218
3219 /* NOTE: Adapted from decode_line_2 in symtab.c, with which it ought
3220    to be re-integrated one of these days.  */
3221
3222 int
3223 user_select_syms (struct ada_symbol_info *syms, int nsyms, int max_results)
3224 {
3225   int i;
3226   int *chosen = (int *) alloca (sizeof (int) * nsyms);
3227   int n_chosen;
3228   int first_choice = (max_results == 1) ? 1 : 2;
3229   const char *select_mode = multiple_symbols_select_mode ();
3230
3231   if (max_results < 1)
3232     error (_("Request to select 0 symbols!"));
3233   if (nsyms <= 1)
3234     return nsyms;
3235
3236   if (select_mode == multiple_symbols_cancel)
3237     error (_("\
3238 canceled because the command is ambiguous\n\
3239 See set/show multiple-symbol."));
3240   
3241   /* If select_mode is "all", then return all possible symbols.
3242      Only do that if more than one symbol can be selected, of course.
3243      Otherwise, display the menu as usual.  */
3244   if (select_mode == multiple_symbols_all && max_results > 1)
3245     return nsyms;
3246
3247   printf_unfiltered (_("[0] cancel\n"));
3248   if (max_results > 1)
3249     printf_unfiltered (_("[1] all\n"));
3250
3251   sort_choices (syms, nsyms);
3252
3253   for (i = 0; i < nsyms; i += 1)
3254     {
3255       if (syms[i].sym == NULL)
3256         continue;
3257
3258       if (SYMBOL_CLASS (syms[i].sym) == LOC_BLOCK)
3259         {
3260           struct symtab_and_line sal =
3261             find_function_start_sal (syms[i].sym, 1);
3262           if (sal.symtab == NULL)
3263             printf_unfiltered (_("[%d] %s at <no source file available>:%d\n"),
3264                                i + first_choice,
3265                                SYMBOL_PRINT_NAME (syms[i].sym),
3266                                sal.line);
3267           else
3268             printf_unfiltered (_("[%d] %s at %s:%d\n"), i + first_choice,
3269                                SYMBOL_PRINT_NAME (syms[i].sym),
3270                                sal.symtab->filename, sal.line);
3271           continue;
3272         }
3273       else
3274         {
3275           int is_enumeral =
3276             (SYMBOL_CLASS (syms[i].sym) == LOC_CONST
3277              && SYMBOL_TYPE (syms[i].sym) != NULL
3278              && TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) == TYPE_CODE_ENUM);
3279           struct symtab *symtab = symtab_for_sym (syms[i].sym);
3280
3281           if (SYMBOL_LINE (syms[i].sym) != 0 && symtab != NULL)
3282             printf_unfiltered (_("[%d] %s at %s:%d\n"),
3283                                i + first_choice,
3284                                SYMBOL_PRINT_NAME (syms[i].sym),
3285                                symtab->filename, SYMBOL_LINE (syms[i].sym));
3286           else if (is_enumeral
3287                    && TYPE_NAME (SYMBOL_TYPE (syms[i].sym)) != NULL)
3288             {
3289               printf_unfiltered (("[%d] "), i + first_choice);
3290               ada_print_type (SYMBOL_TYPE (syms[i].sym), NULL,
3291                               gdb_stdout, -1, 0);
3292               printf_unfiltered (_("'(%s) (enumeral)\n"),
3293                                  SYMBOL_PRINT_NAME (syms[i].sym));
3294             }
3295           else if (symtab != NULL)
3296             printf_unfiltered (is_enumeral
3297                                ? _("[%d] %s in %s (enumeral)\n")
3298                                : _("[%d] %s at %s:?\n"),
3299                                i + first_choice,
3300                                SYMBOL_PRINT_NAME (syms[i].sym),
3301                                symtab->filename);
3302           else
3303             printf_unfiltered (is_enumeral
3304                                ? _("[%d] %s (enumeral)\n")
3305                                : _("[%d] %s at ?\n"),
3306                                i + first_choice,
3307                                SYMBOL_PRINT_NAME (syms[i].sym));
3308         }
3309     }
3310
3311   n_chosen = get_selections (chosen, nsyms, max_results, max_results > 1,
3312                              "overload-choice");
3313
3314   for (i = 0; i < n_chosen; i += 1)
3315     syms[i] = syms[chosen[i]];
3316
3317   return n_chosen;
3318 }
3319
3320 /* Read and validate a set of numeric choices from the user in the
3321    range 0 .. N_CHOICES-1.  Place the results in increasing
3322    order in CHOICES[0 .. N-1], and return N.
3323
3324    The user types choices as a sequence of numbers on one line
3325    separated by blanks, encoding them as follows:
3326
3327      + A choice of 0 means to cancel the selection, throwing an error.
3328      + If IS_ALL_CHOICE, a choice of 1 selects the entire set 0 .. N_CHOICES-1.
3329      + The user chooses k by typing k+IS_ALL_CHOICE+1.
3330
3331    The user is not allowed to choose more than MAX_RESULTS values.
3332
3333    ANNOTATION_SUFFIX, if present, is used to annotate the input
3334    prompts (for use with the -f switch).  */
3335
3336 int
3337 get_selections (int *choices, int n_choices, int max_results,
3338                 int is_all_choice, char *annotation_suffix)
3339 {
3340   char *args;
3341   char *prompt;
3342   int n_chosen;
3343   int first_choice = is_all_choice ? 2 : 1;
3344
3345   prompt = getenv ("PS2");
3346   if (prompt == NULL)
3347     prompt = "> ";
3348
3349   args = command_line_input (prompt, 0, annotation_suffix);
3350
3351   if (args == NULL)
3352     error_no_arg (_("one or more choice numbers"));
3353
3354   n_chosen = 0;
3355
3356   /* Set choices[0 .. n_chosen-1] to the users' choices in ascending
3357      order, as given in args.  Choices are validated.  */
3358   while (1)
3359     {
3360       char *args2;
3361       int choice, j;
3362
3363       while (isspace (*args))
3364         args += 1;
3365       if (*args == '\0' && n_chosen == 0)
3366         error_no_arg (_("one or more choice numbers"));
3367       else if (*args == '\0')
3368         break;
3369
3370       choice = strtol (args, &args2, 10);
3371       if (args == args2 || choice < 0
3372           || choice > n_choices + first_choice - 1)
3373         error (_("Argument must be choice number"));
3374       args = args2;
3375
3376       if (choice == 0)
3377         error (_("cancelled"));
3378
3379       if (choice < first_choice)
3380         {
3381           n_chosen = n_choices;
3382           for (j = 0; j < n_choices; j += 1)
3383             choices[j] = j;
3384           break;
3385         }
3386       choice -= first_choice;
3387
3388       for (j = n_chosen - 1; j >= 0 && choice < choices[j]; j -= 1)
3389         {
3390         }
3391
3392       if (j < 0 || choice != choices[j])
3393         {
3394           int k;
3395           for (k = n_chosen - 1; k > j; k -= 1)
3396             choices[k + 1] = choices[k];
3397           choices[j + 1] = choice;
3398           n_chosen += 1;
3399         }
3400     }
3401
3402   if (n_chosen > max_results)
3403     error (_("Select no more than %d of the above"), max_results);
3404
3405   return n_chosen;
3406 }
3407
3408 /* Replace the operator of length OPLEN at position PC in *EXPP with a call
3409    on the function identified by SYM and BLOCK, and taking NARGS
3410    arguments.  Update *EXPP as needed to hold more space.  */
3411
3412 static void
3413 replace_operator_with_call (struct expression **expp, int pc, int nargs,
3414                             int oplen, struct symbol *sym,
3415                             struct block *block)
3416 {
3417   /* A new expression, with 6 more elements (3 for funcall, 4 for function
3418      symbol, -oplen for operator being replaced).  */
3419   struct expression *newexp = (struct expression *)
3420     xmalloc (sizeof (struct expression)
3421              + EXP_ELEM_TO_BYTES ((*expp)->nelts + 7 - oplen));
3422   struct expression *exp = *expp;
3423
3424   newexp->nelts = exp->nelts + 7 - oplen;
3425   newexp->language_defn = exp->language_defn;
3426   memcpy (newexp->elts, exp->elts, EXP_ELEM_TO_BYTES (pc));
3427   memcpy (newexp->elts + pc + 7, exp->elts + pc + oplen,
3428           EXP_ELEM_TO_BYTES (exp->nelts - pc - oplen));
3429
3430   newexp->elts[pc].opcode = newexp->elts[pc + 2].opcode = OP_FUNCALL;
3431   newexp->elts[pc + 1].longconst = (LONGEST) nargs;
3432
3433   newexp->elts[pc + 3].opcode = newexp->elts[pc + 6].opcode = OP_VAR_VALUE;
3434   newexp->elts[pc + 4].block = block;
3435   newexp->elts[pc + 5].symbol = sym;
3436
3437   *expp = newexp;
3438   xfree (exp);
3439 }
3440
3441 /* Type-class predicates */
3442
3443 /* True iff TYPE is numeric (i.e., an INT, RANGE (of numeric type),
3444    or FLOAT).  */
3445
3446 static int
3447 numeric_type_p (struct type *type)
3448 {
3449   if (type == NULL)
3450     return 0;
3451   else
3452     {
3453       switch (TYPE_CODE (type))
3454         {
3455         case TYPE_CODE_INT:
3456         case TYPE_CODE_FLT:
3457           return 1;
3458         case TYPE_CODE_RANGE:
3459           return (type == TYPE_TARGET_TYPE (type)
3460                   || numeric_type_p (TYPE_TARGET_TYPE (type)));
3461         default:
3462           return 0;
3463         }
3464     }
3465 }
3466
3467 /* True iff TYPE is integral (an INT or RANGE of INTs).  */
3468
3469 static int
3470 integer_type_p (struct type *type)
3471 {
3472   if (type == NULL)
3473     return 0;
3474   else
3475     {
3476       switch (TYPE_CODE (type))
3477         {
3478         case TYPE_CODE_INT:
3479           return 1;
3480         case TYPE_CODE_RANGE:
3481           return (type == TYPE_TARGET_TYPE (type)
3482                   || integer_type_p (TYPE_TARGET_TYPE (type)));
3483         default:
3484           return 0;
3485         }
3486     }
3487 }
3488
3489 /* True iff TYPE is scalar (INT, RANGE, FLOAT, ENUM).  */
3490
3491 static int
3492 scalar_type_p (struct type *type)
3493 {
3494   if (type == NULL)
3495     return 0;
3496   else
3497     {
3498       switch (TYPE_CODE (type))
3499         {
3500         case TYPE_CODE_INT:
3501         case TYPE_CODE_RANGE:
3502         case TYPE_CODE_ENUM:
3503         case TYPE_CODE_FLT:
3504           return 1;
3505         default:
3506           return 0;
3507         }
3508     }
3509 }
3510
3511 /* True iff TYPE is discrete (INT, RANGE, ENUM).  */
3512
3513 static int
3514 discrete_type_p (struct type *type)
3515 {
3516   if (type == NULL)
3517     return 0;
3518   else
3519     {
3520       switch (TYPE_CODE (type))
3521         {
3522         case TYPE_CODE_INT:
3523         case TYPE_CODE_RANGE:
3524         case TYPE_CODE_ENUM:
3525           return 1;
3526         default:
3527           return 0;
3528         }
3529     }
3530 }
3531
3532 /* Returns non-zero if OP with operands in the vector ARGS could be
3533    a user-defined function.  Errs on the side of pre-defined operators
3534    (i.e., result 0).  */
3535
3536 static int
3537 possible_user_operator_p (enum exp_opcode op, struct value *args[])
3538 {
3539   struct type *type0 =
3540     (args[0] == NULL) ? NULL : ada_check_typedef (value_type (args[0]));
3541   struct type *type1 =
3542     (args[1] == NULL) ? NULL : ada_check_typedef (value_type (args[1]));
3543
3544   if (type0 == NULL)
3545     return 0;
3546
3547   switch (op)
3548     {
3549     default:
3550       return 0;
3551
3552     case BINOP_ADD:
3553     case BINOP_SUB:
3554     case BINOP_MUL:
3555     case BINOP_DIV:
3556       return (!(numeric_type_p (type0) && numeric_type_p (type1)));
3557
3558     case BINOP_REM:
3559     case BINOP_MOD:
3560     case BINOP_BITWISE_AND:
3561     case BINOP_BITWISE_IOR:
3562     case BINOP_BITWISE_XOR:
3563       return (!(integer_type_p (type0) && integer_type_p (type1)));
3564
3565     case BINOP_EQUAL:
3566     case BINOP_NOTEQUAL:
3567     case BINOP_LESS:
3568     case BINOP_GTR:
3569     case BINOP_LEQ:
3570     case BINOP_GEQ:
3571       return (!(scalar_type_p (type0) && scalar_type_p (type1)));
3572
3573     case BINOP_CONCAT:
3574       return !ada_is_array_type (type0) || !ada_is_array_type (type1);
3575
3576     case BINOP_EXP:
3577       return (!(numeric_type_p (type0) && integer_type_p (type1)));
3578
3579     case UNOP_NEG:
3580     case UNOP_PLUS:
3581     case UNOP_LOGICAL_NOT:
3582     case UNOP_ABS:
3583       return (!numeric_type_p (type0));
3584
3585     }
3586 }
3587 \f
3588                                 /* Renaming */
3589
3590 /* NOTES: 
3591
3592    1. In the following, we assume that a renaming type's name may
3593       have an ___XD suffix.  It would be nice if this went away at some
3594       point.
3595    2. We handle both the (old) purely type-based representation of 
3596       renamings and the (new) variable-based encoding.  At some point,
3597       it is devoutly to be hoped that the former goes away 
3598       (FIXME: hilfinger-2007-07-09).
3599    3. Subprogram renamings are not implemented, although the XRS
3600       suffix is recognized (FIXME: hilfinger-2007-07-09).  */
3601
3602 /* If SYM encodes a renaming, 
3603
3604        <renaming> renames <renamed entity>,
3605
3606    sets *LEN to the length of the renamed entity's name,
3607    *RENAMED_ENTITY to that name (not null-terminated), and *RENAMING_EXPR to
3608    the string describing the subcomponent selected from the renamed
3609    entity. Returns ADA_NOT_RENAMING if SYM does not encode a renaming
3610    (in which case, the values of *RENAMED_ENTITY, *LEN, and *RENAMING_EXPR
3611    are undefined).  Otherwise, returns a value indicating the category
3612    of entity renamed: an object (ADA_OBJECT_RENAMING), exception
3613    (ADA_EXCEPTION_RENAMING), package (ADA_PACKAGE_RENAMING), or
3614    subprogram (ADA_SUBPROGRAM_RENAMING).  Does no allocation; the
3615    strings returned in *RENAMED_ENTITY and *RENAMING_EXPR should not be
3616    deallocated.  The values of RENAMED_ENTITY, LEN, or RENAMING_EXPR
3617    may be NULL, in which case they are not assigned.
3618
3619    [Currently, however, GCC does not generate subprogram renamings.]  */
3620
3621 enum ada_renaming_category
3622 ada_parse_renaming (struct symbol *sym,
3623                     const char **renamed_entity, int *len, 
3624                     const char **renaming_expr)
3625 {
3626   enum ada_renaming_category kind;
3627   const char *info;
3628   const char *suffix;
3629
3630   if (sym == NULL)
3631     return ADA_NOT_RENAMING;
3632   switch (SYMBOL_CLASS (sym)) 
3633     {
3634     default:
3635       return ADA_NOT_RENAMING;
3636     case LOC_TYPEDEF:
3637       return parse_old_style_renaming (SYMBOL_TYPE (sym), 
3638                                        renamed_entity, len, renaming_expr);
3639     case LOC_LOCAL:
3640     case LOC_STATIC:
3641     case LOC_COMPUTED:
3642     case LOC_OPTIMIZED_OUT:
3643       info = strstr (SYMBOL_LINKAGE_NAME (sym), "___XR");
3644       if (info == NULL)
3645         return ADA_NOT_RENAMING;
3646       switch (info[5])
3647         {
3648         case '_':
3649           kind = ADA_OBJECT_RENAMING;
3650           info += 6;
3651           break;
3652         case 'E':
3653           kind = ADA_EXCEPTION_RENAMING;
3654           info += 7;
3655           break;
3656         case 'P':
3657           kind = ADA_PACKAGE_RENAMING;
3658           info += 7;
3659           break;
3660         case 'S':
3661           kind = ADA_SUBPROGRAM_RENAMING;
3662           info += 7;
3663           break;
3664         default:
3665           return ADA_NOT_RENAMING;
3666         }
3667     }
3668
3669   if (renamed_entity != NULL)
3670     *renamed_entity = info;
3671   suffix = strstr (info, "___XE");
3672   if (suffix == NULL || suffix == info)
3673     return ADA_NOT_RENAMING;
3674   if (len != NULL)
3675     *len = strlen (info) - strlen (suffix);
3676   suffix += 5;
3677   if (renaming_expr != NULL)
3678     *renaming_expr = suffix;
3679   return kind;
3680 }
3681
3682 /* Assuming TYPE encodes a renaming according to the old encoding in
3683    exp_dbug.ads, returns details of that renaming in *RENAMED_ENTITY,
3684    *LEN, and *RENAMING_EXPR, as for ada_parse_renaming, above.  Returns
3685    ADA_NOT_RENAMING otherwise.  */
3686 static enum ada_renaming_category
3687 parse_old_style_renaming (struct type *type,
3688                           const char **renamed_entity, int *len, 
3689                           const char **renaming_expr)
3690 {
3691   enum ada_renaming_category kind;
3692   const char *name;
3693   const char *info;
3694   const char *suffix;
3695
3696   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_ENUM 
3697       || TYPE_NFIELDS (type) != 1)
3698     return ADA_NOT_RENAMING;
3699
3700   name = type_name_no_tag (type);
3701   if (name == NULL)
3702     return ADA_NOT_RENAMING;
3703   
3704   name = strstr (name, "___XR");
3705   if (name == NULL)
3706     return ADA_NOT_RENAMING;
3707   switch (name[5])
3708     {
3709     case '\0':
3710     case '_':
3711       kind = ADA_OBJECT_RENAMING;
3712       break;
3713     case 'E':
3714       kind = ADA_EXCEPTION_RENAMING;
3715       break;
3716     case 'P':
3717       kind = ADA_PACKAGE_RENAMING;
3718       break;
3719     case 'S':
3720       kind = ADA_SUBPROGRAM_RENAMING;
3721       break;
3722     default:
3723       return ADA_NOT_RENAMING;
3724     }
3725
3726   info = TYPE_FIELD_NAME (type, 0);
3727   if (info == NULL)
3728     return ADA_NOT_RENAMING;
3729   if (renamed_entity != NULL)
3730     *renamed_entity = info;
3731   suffix = strstr (info, "___XE");
3732   if (renaming_expr != NULL)
3733     *renaming_expr = suffix + 5;
3734   if (suffix == NULL || suffix == info)
3735     return ADA_NOT_RENAMING;
3736   if (len != NULL)
3737     *len = suffix - info;
3738   return kind;
3739 }  
3740
3741 \f
3742
3743                                 /* Evaluation: Function Calls */
3744
3745 /* Return an lvalue containing the value VAL.  This is the identity on
3746    lvalues, and otherwise has the side-effect of pushing a copy of VAL 
3747    on the stack, using and updating *SP as the stack pointer, and 
3748    returning an lvalue whose VALUE_ADDRESS points to the copy.  */
3749
3750 static struct value *
3751 ensure_lval (struct value *val, CORE_ADDR *sp)
3752 {
3753   if (! VALUE_LVAL (val))
3754     {
3755       int len = TYPE_LENGTH (ada_check_typedef (value_type (val)));
3756
3757       /* The following is taken from the structure-return code in
3758          call_function_by_hand. FIXME: Therefore, some refactoring seems 
3759          indicated. */
3760       if (gdbarch_inner_than (current_gdbarch, 1, 2))
3761         {
3762           /* Stack grows downward.  Align SP and VALUE_ADDRESS (val) after
3763              reserving sufficient space. */
3764           *sp -= len;
3765           if (gdbarch_frame_align_p (current_gdbarch))
3766             *sp = gdbarch_frame_align (current_gdbarch, *sp);
3767           VALUE_ADDRESS (val) = *sp;
3768         }
3769       else
3770         {
3771           /* Stack grows upward.  Align the frame, allocate space, and
3772              then again, re-align the frame. */
3773           if (gdbarch_frame_align_p (current_gdbarch))
3774             *sp = gdbarch_frame_align (current_gdbarch, *sp);
3775           VALUE_ADDRESS (val) = *sp;
3776           *sp += len;
3777           if (gdbarch_frame_align_p (current_gdbarch))
3778             *sp = gdbarch_frame_align (current_gdbarch, *sp);
3779         }
3780       VALUE_LVAL (val) = lval_memory;
3781
3782       write_memory (VALUE_ADDRESS (val), value_contents_raw (val), len);
3783     }
3784
3785   return val;
3786 }
3787
3788 /* Return the value ACTUAL, converted to be an appropriate value for a
3789    formal of type FORMAL_TYPE.  Use *SP as a stack pointer for
3790    allocating any necessary descriptors (fat pointers), or copies of
3791    values not residing in memory, updating it as needed.  */
3792
3793 struct value *
3794 ada_convert_actual (struct value *actual, struct type *formal_type0,
3795                     CORE_ADDR *sp)
3796 {
3797   struct type *actual_type = ada_check_typedef (value_type (actual));
3798   struct type *formal_type = ada_check_typedef (formal_type0);
3799   struct type *formal_target =
3800     TYPE_CODE (formal_type) == TYPE_CODE_PTR
3801     ? ada_check_typedef (TYPE_TARGET_TYPE (formal_type)) : formal_type;
3802   struct type *actual_target =
3803     TYPE_CODE (actual_type) == TYPE_CODE_PTR
3804     ? ada_check_typedef (TYPE_TARGET_TYPE (actual_type)) : actual_type;
3805
3806   if (ada_is_array_descriptor_type (formal_target)
3807       && TYPE_CODE (actual_target) == TYPE_CODE_ARRAY)
3808     return make_array_descriptor (formal_type, actual, sp);
3809   else if (TYPE_CODE (formal_type) == TYPE_CODE_PTR
3810            || TYPE_CODE (formal_type) == TYPE_CODE_REF)
3811     {
3812       struct value *result;
3813       if (TYPE_CODE (formal_target) == TYPE_CODE_ARRAY
3814           && ada_is_array_descriptor_type (actual_target))
3815         result = desc_data (actual);
3816       else if (TYPE_CODE (actual_type) != TYPE_CODE_PTR)
3817         {
3818           if (VALUE_LVAL (actual) != lval_memory)
3819             {
3820               struct value *val;
3821               actual_type = ada_check_typedef (value_type (actual));
3822               val = allocate_value (actual_type);
3823               memcpy ((char *) value_contents_raw (val),
3824                       (char *) value_contents (actual),
3825                       TYPE_LENGTH (actual_type));
3826               actual = ensure_lval (val, sp);
3827             }
3828           result = value_addr (actual);
3829         }
3830       else
3831         return actual;
3832       return value_cast_pointers (formal_type, result);
3833     }
3834   else if (TYPE_CODE (actual_type) == TYPE_CODE_PTR)
3835     return ada_value_ind (actual);
3836
3837   return actual;
3838 }
3839
3840
3841 /* Push a descriptor of type TYPE for array value ARR on the stack at
3842    *SP, updating *SP to reflect the new descriptor.  Return either
3843    an lvalue representing the new descriptor, or (if TYPE is a pointer-
3844    to-descriptor type rather than a descriptor type), a struct value *
3845    representing a pointer to this descriptor.  */
3846
3847 static struct value *
3848 make_array_descriptor (struct type *type, struct value *arr, CORE_ADDR *sp)
3849 {
3850   struct type *bounds_type = desc_bounds_type (type);
3851   struct type *desc_type = desc_base_type (type);
3852   struct value *descriptor = allocate_value (desc_type);
3853   struct value *bounds = allocate_value (bounds_type);
3854   int i;
3855
3856   for (i = ada_array_arity (ada_check_typedef (value_type (arr))); i > 0; i -= 1)
3857     {
3858       modify_general_field (value_contents_writeable (bounds),
3859                             value_as_long (ada_array_bound (arr, i, 0)),
3860                             desc_bound_bitpos (bounds_type, i, 0),
3861                             desc_bound_bitsize (bounds_type, i, 0));
3862       modify_general_field (value_contents_writeable (bounds),
3863                             value_as_long (ada_array_bound (arr, i, 1)),
3864                             desc_bound_bitpos (bounds_type, i, 1),
3865                             desc_bound_bitsize (bounds_type, i, 1));
3866     }
3867
3868   bounds = ensure_lval (bounds, sp);
3869
3870   modify_general_field (value_contents_writeable (descriptor),
3871                         VALUE_ADDRESS (ensure_lval (arr, sp)),
3872                         fat_pntr_data_bitpos (desc_type),
3873                         fat_pntr_data_bitsize (desc_type));
3874
3875   modify_general_field (value_contents_writeable (descriptor),
3876                         VALUE_ADDRESS (bounds),
3877                         fat_pntr_bounds_bitpos (desc_type),
3878                         fat_pntr_bounds_bitsize (desc_type));
3879
3880   descriptor = ensure_lval (descriptor, sp);
3881
3882   if (TYPE_CODE (type) == TYPE_CODE_PTR)
3883     return value_addr (descriptor);
3884   else
3885     return descriptor;
3886 }
3887 \f
3888 /* Dummy definitions for an experimental caching module that is not
3889  * used in the public sources. */
3890
3891 static int
3892 lookup_cached_symbol (const char *name, domain_enum namespace,
3893                       struct symbol **sym, struct block **block)
3894 {
3895   return 0;
3896 }
3897
3898 static void
3899 cache_symbol (const char *name, domain_enum namespace, struct symbol *sym,
3900               struct block *block)
3901 {
3902 }
3903 \f
3904                                 /* Symbol Lookup */
3905
3906 /* Return the result of a standard (literal, C-like) lookup of NAME in
3907    given DOMAIN, visible from lexical block BLOCK.  */
3908
3909 static struct symbol *
3910 standard_lookup (const char *name, const struct block *block,
3911                  domain_enum domain)
3912 {
3913   struct symbol *sym;
3914
3915   if (lookup_cached_symbol (name, domain, &sym, NULL))
3916     return sym;
3917   sym = lookup_symbol_in_language (name, block, domain, language_c, 0);
3918   cache_symbol (name, domain, sym, block_found);
3919   return sym;
3920 }
3921
3922
3923 /* Non-zero iff there is at least one non-function/non-enumeral symbol
3924    in the symbol fields of SYMS[0..N-1].  We treat enumerals as functions, 
3925    since they contend in overloading in the same way.  */
3926 static int
3927 is_nonfunction (struct ada_symbol_info syms[], int n)
3928 {
3929   int i;
3930
3931   for (i = 0; i < n; i += 1)
3932     if (TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) != TYPE_CODE_FUNC
3933         && (TYPE_CODE (SYMBOL_TYPE (syms[i].sym)) != TYPE_CODE_ENUM
3934             || SYMBOL_CLASS (syms[i].sym) != LOC_CONST))
3935       return 1;
3936
3937   return 0;
3938 }
3939
3940 /* If true (non-zero), then TYPE0 and TYPE1 represent equivalent
3941    struct types.  Otherwise, they may not.  */
3942
3943 static int
3944 equiv_types (struct type *type0, struct type *type1)
3945 {
3946   if (type0 == type1)
3947     return 1;
3948   if (type0 == NULL || type1 == NULL
3949       || TYPE_CODE (type0) != TYPE_CODE (type1))
3950     return 0;
3951   if ((TYPE_CODE (type0) == TYPE_CODE_STRUCT
3952        || TYPE_CODE (type0) == TYPE_CODE_ENUM)
3953       && ada_type_name (type0) != NULL && ada_type_name (type1) != NULL
3954       && strcmp (ada_type_name (type0), ada_type_name (type1)) == 0)
3955     return 1;
3956
3957   return 0;
3958 }
3959
3960 /* True iff SYM0 represents the same entity as SYM1, or one that is
3961    no more defined than that of SYM1.  */
3962
3963 static int
3964 lesseq_defined_than (struct symbol *sym0, struct symbol *sym1)
3965 {
3966   if (sym0 == sym1)
3967     return 1;
3968   if (SYMBOL_DOMAIN (sym0) != SYMBOL_DOMAIN (sym1)
3969       || SYMBOL_CLASS (sym0) != SYMBOL_CLASS (sym1))
3970     return 0;
3971
3972   switch (SYMBOL_CLASS (sym0))
3973     {
3974     case LOC_UNDEF:
3975       return 1;
3976     case LOC_TYPEDEF:
3977       {
3978         struct type *type0 = SYMBOL_TYPE (sym0);
3979         struct type *type1 = SYMBOL_TYPE (sym1);
3980         char *name0 = SYMBOL_LINKAGE_NAME (sym0);
3981         char *name1 = SYMBOL_LINKAGE_NAME (sym1);
3982         int len0 = strlen (name0);
3983         return
3984           TYPE_CODE (type0) == TYPE_CODE (type1)
3985           && (equiv_types (type0, type1)
3986               || (len0 < strlen (name1) && strncmp (name0, name1, len0) == 0
3987                   && strncmp (name1 + len0, "___XV", 5) == 0));
3988       }
3989     case LOC_CONST:
3990       return SYMBOL_VALUE (sym0) == SYMBOL_VALUE (sym1)
3991         && equiv_types (SYMBOL_TYPE (sym0), SYMBOL_TYPE (sym1));
3992     default:
3993       return 0;
3994     }
3995 }
3996
3997 /* Append (SYM,BLOCK,SYMTAB) to the end of the array of struct ada_symbol_info
3998    records in OBSTACKP.  Do nothing if SYM is a duplicate.  */
3999
4000 static void
4001 add_defn_to_vec (struct obstack *obstackp,
4002                  struct symbol *sym,
4003                  struct block *block)
4004 {
4005   int i;
4006   size_t tmp;
4007   struct ada_symbol_info *prevDefns = defns_collected (obstackp, 0);
4008
4009   /* Do not try to complete stub types, as the debugger is probably
4010      already scanning all symbols matching a certain name at the
4011      time when this function is called.  Trying to replace the stub
4012      type by its associated full type will cause us to restart a scan
4013      which may lead to an infinite recursion.  Instead, the client
4014      collecting the matching symbols will end up collecting several
4015      matches, with at least one of them complete.  It can then filter
4016      out the stub ones if needed.  */
4017
4018   for (i = num_defns_collected (obstackp) - 1; i >= 0; i -= 1)
4019     {
4020       if (lesseq_defined_than (sym, prevDefns[i].sym))
4021         return;
4022       else if (lesseq_defined_than (prevDefns[i].sym, sym))
4023         {
4024           prevDefns[i].sym = sym;
4025           prevDefns[i].block = block;
4026           return;
4027         }
4028     }
4029
4030   {
4031     struct ada_symbol_info info;
4032
4033     info.sym = sym;
4034     info.block = block;
4035     obstack_grow (obstackp, &info, sizeof (struct ada_symbol_info));
4036   }
4037 }
4038
4039 /* Number of ada_symbol_info structures currently collected in 
4040    current vector in *OBSTACKP.  */
4041
4042 static int
4043 num_defns_collected (struct obstack *obstackp)
4044 {
4045   return obstack_object_size (obstackp) / sizeof (struct ada_symbol_info);
4046 }
4047
4048 /* Vector of ada_symbol_info structures currently collected in current 
4049    vector in *OBSTACKP.  If FINISH, close off the vector and return
4050    its final address.  */
4051
4052 static struct ada_symbol_info *
4053 defns_collected (struct obstack *obstackp, int finish)
4054 {
4055   if (finish)
4056     return obstack_finish (obstackp);
4057   else
4058     return (struct ada_symbol_info *) obstack_base (obstackp);
4059 }
4060
4061 /* Look, in partial_symtab PST, for symbol NAME in given namespace.
4062    Check the global symbols if GLOBAL, the static symbols if not.
4063    Do wild-card match if WILD.  */
4064
4065 static struct partial_symbol *
4066 ada_lookup_partial_symbol (struct partial_symtab *pst, const char *name,
4067                            int global, domain_enum namespace, int wild)
4068 {
4069   struct partial_symbol **start;
4070   int name_len = strlen (name);
4071   int length = (global ? pst->n_global_syms : pst->n_static_syms);
4072   int i;
4073
4074   if (length == 0)
4075     {
4076       return (NULL);
4077     }
4078
4079   start = (global ?
4080            pst->objfile->global_psymbols.list + pst->globals_offset :
4081            pst->objfile->static_psymbols.list + pst->statics_offset);
4082
4083   if (wild)
4084     {
4085       for (i = 0; i < length; i += 1)
4086         {
4087           struct partial_symbol *psym = start[i];
4088
4089           if (symbol_matches_domain (SYMBOL_LANGUAGE (psym),
4090                                      SYMBOL_DOMAIN (psym), namespace)
4091               && wild_match (name, name_len, SYMBOL_LINKAGE_NAME (psym)))
4092             return psym;
4093         }
4094       return NULL;
4095     }
4096   else
4097     {
4098       if (global)
4099         {
4100           int U;
4101           i = 0;
4102           U = length - 1;
4103           while (U - i > 4)
4104             {
4105               int M = (U + i) >> 1;
4106               struct partial_symbol *psym = start[M];
4107               if (SYMBOL_LINKAGE_NAME (psym)[0] < name[0])
4108                 i = M + 1;
4109               else if (SYMBOL_LINKAGE_NAME (psym)[0] > name[0])
4110                 U = M - 1;
4111               else if (strcmp (SYMBOL_LINKAGE_NAME (psym), name) < 0)
4112                 i = M + 1;
4113               else
4114                 U = M;
4115             }
4116         }
4117       else
4118         i = 0;
4119
4120       while (i < length)
4121         {
4122           struct partial_symbol *psym = start[i];
4123
4124           if (symbol_matches_domain (SYMBOL_LANGUAGE (psym),
4125                                      SYMBOL_DOMAIN (psym), namespace))
4126             {
4127               int cmp = strncmp (name, SYMBOL_LINKAGE_NAME (psym), name_len);
4128
4129               if (cmp < 0)
4130                 {
4131                   if (global)
4132                     break;
4133                 }
4134               else if (cmp == 0
4135                        && is_name_suffix (SYMBOL_LINKAGE_NAME (psym)
4136                                           + name_len))
4137                 return psym;
4138             }
4139           i += 1;
4140         }
4141
4142       if (global)
4143         {
4144           int U;
4145           i = 0;
4146           U = length - 1;
4147           while (U - i > 4)
4148             {
4149               int M = (U + i) >> 1;
4150               struct partial_symbol *psym = start[M];
4151               if (SYMBOL_LINKAGE_NAME (psym)[0] < '_')
4152                 i = M + 1;
4153               else if (SYMBOL_LINKAGE_NAME (psym)[0] > '_')
4154                 U = M - 1;
4155               else if (strcmp (SYMBOL_LINKAGE_NAME (psym), "_ada_") < 0)
4156                 i = M + 1;
4157               else
4158                 U = M;
4159             }
4160         }
4161       else
4162         i = 0;
4163
4164       while (i < length)
4165         {
4166           struct partial_symbol *psym = start[i];
4167
4168           if (symbol_matches_domain (SYMBOL_LANGUAGE (psym),
4169                                      SYMBOL_DOMAIN (psym), namespace))
4170             {
4171               int cmp;
4172
4173               cmp = (int) '_' - (int) SYMBOL_LINKAGE_NAME (psym)[0];
4174               if (cmp == 0)
4175                 {
4176                   cmp = strncmp ("_ada_", SYMBOL_LINKAGE_NAME (psym), 5);
4177                   if (cmp == 0)
4178                     cmp = strncmp (name, SYMBOL_LINKAGE_NAME (psym) + 5,
4179                                    name_len);
4180                 }
4181
4182               if (cmp < 0)
4183                 {
4184                   if (global)
4185                     break;
4186                 }
4187               else if (cmp == 0
4188                        && is_name_suffix (SYMBOL_LINKAGE_NAME (psym)
4189                                           + name_len + 5))
4190                 return psym;
4191             }
4192           i += 1;
4193         }
4194     }
4195   return NULL;
4196 }
4197
4198 /* Find a symbol table containing symbol SYM or NULL if none.  */
4199
4200 static struct symtab *
4201 symtab_for_sym (struct symbol *sym)
4202 {
4203   struct symtab *s;
4204   struct objfile *objfile;
4205   struct block *b;
4206   struct symbol *tmp_sym;
4207   struct dict_iterator iter;
4208   int j;
4209
4210   ALL_PRIMARY_SYMTABS (objfile, s)
4211   {
4212     switch (SYMBOL_CLASS (sym))
4213       {
4214       case LOC_CONST:
4215       case LOC_STATIC:
4216       case LOC_TYPEDEF:
4217       case LOC_REGISTER:
4218       case LOC_LABEL:
4219       case LOC_BLOCK:
4220       case LOC_CONST_BYTES:
4221         b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), GLOBAL_BLOCK);
4222         ALL_BLOCK_SYMBOLS (b, iter, tmp_sym) if (sym == tmp_sym)
4223           return s;
4224         b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), STATIC_BLOCK);
4225         ALL_BLOCK_SYMBOLS (b, iter, tmp_sym) if (sym == tmp_sym)
4226           return s;
4227         break;
4228       default:
4229         break;
4230       }
4231     switch (SYMBOL_CLASS (sym))
4232       {
4233       case LOC_REGISTER:
4234       case LOC_ARG:
4235       case LOC_REF_ARG:
4236       case LOC_REGPARM_ADDR:
4237       case LOC_LOCAL:
4238       case LOC_TYPEDEF:
4239       case LOC_COMPUTED:
4240         for (j = FIRST_LOCAL_BLOCK;
4241              j < BLOCKVECTOR_NBLOCKS (BLOCKVECTOR (s)); j += 1)
4242           {
4243             b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), j);
4244             ALL_BLOCK_SYMBOLS (b, iter, tmp_sym) if (sym == tmp_sym)
4245               return s;
4246           }
4247         break;
4248       default:
4249         break;
4250       }
4251   }
4252   return NULL;
4253 }
4254
4255 /* Return a minimal symbol matching NAME according to Ada decoding
4256    rules.  Returns NULL if there is no such minimal symbol.  Names 
4257    prefixed with "standard__" are handled specially: "standard__" is 
4258    first stripped off, and only static and global symbols are searched.  */
4259
4260 struct minimal_symbol *
4261 ada_lookup_simple_minsym (const char *name)
4262 {
4263   struct objfile *objfile;
4264   struct minimal_symbol *msymbol;
4265   int wild_match;
4266
4267   if (strncmp (name, "standard__", sizeof ("standard__") - 1) == 0)
4268     {
4269       name += sizeof ("standard__") - 1;
4270       wild_match = 0;
4271     }
4272   else
4273     wild_match = (strstr (name, "__") == NULL);
4274
4275   ALL_MSYMBOLS (objfile, msymbol)
4276   {
4277     if (ada_match_name (SYMBOL_LINKAGE_NAME (msymbol), name, wild_match)
4278         && MSYMBOL_TYPE (msymbol) != mst_solib_trampoline)
4279       return msymbol;
4280   }
4281
4282   return NULL;
4283 }
4284
4285 /* For all subprograms that statically enclose the subprogram of the
4286    selected frame, add symbols matching identifier NAME in DOMAIN
4287    and their blocks to the list of data in OBSTACKP, as for
4288    ada_add_block_symbols (q.v.).   If WILD, treat as NAME with a
4289    wildcard prefix.  */
4290
4291 static void
4292 add_symbols_from_enclosing_procs (struct obstack *obstackp,
4293                                   const char *name, domain_enum namespace,
4294                                   int wild_match)
4295 {
4296 }
4297
4298 /* True if TYPE is definitely an artificial type supplied to a symbol
4299    for which no debugging information was given in the symbol file.  */
4300
4301 static int
4302 is_nondebugging_type (struct type *type)
4303 {
4304   char *name = ada_type_name (type);
4305   return (name != NULL && strcmp (name, "<variable, no debug info>") == 0);
4306 }
4307
4308 /* Remove any non-debugging symbols in SYMS[0 .. NSYMS-1] that definitely
4309    duplicate other symbols in the list (The only case I know of where
4310    this happens is when object files containing stabs-in-ecoff are
4311    linked with files containing ordinary ecoff debugging symbols (or no
4312    debugging symbols)).  Modifies SYMS to squeeze out deleted entries.
4313    Returns the number of items in the modified list.  */
4314
4315 static int
4316 remove_extra_symbols (struct ada_symbol_info *syms, int nsyms)
4317 {
4318   int i, j;
4319
4320   i = 0;
4321   while (i < nsyms)
4322     {
4323       int remove = 0;
4324
4325       /* If two symbols have the same name and one of them is a stub type,
4326          the get rid of the stub.  */
4327
4328       if (TYPE_STUB (SYMBOL_TYPE (syms[i].sym))
4329           && SYMBOL_LINKAGE_NAME (syms[i].sym) != NULL)
4330         {
4331           for (j = 0; j < nsyms; j++)
4332             {
4333               if (j != i
4334                   && !TYPE_STUB (SYMBOL_TYPE (syms[j].sym))
4335                   && SYMBOL_LINKAGE_NAME (syms[j].sym) != NULL
4336                   && strcmp (SYMBOL_LINKAGE_NAME (syms[i].sym),
4337                              SYMBOL_LINKAGE_NAME (syms[j].sym)) == 0)
4338                 remove = 1;
4339             }
4340         }
4341
4342       /* Two symbols with the same name, same class and same address
4343          should be identical.  */
4344
4345       else if (SYMBOL_LINKAGE_NAME (syms[i].sym) != NULL
4346           && SYMBOL_CLASS (syms[i].sym) == LOC_STATIC
4347           && is_nondebugging_type (SYMBOL_TYPE (syms[i].sym)))
4348         {
4349           for (j = 0; j < nsyms; j += 1)
4350             {
4351               if (i != j
4352                   && SYMBOL_LINKAGE_NAME (syms[j].sym) != NULL
4353                   && strcmp (SYMBOL_LINKAGE_NAME (syms[i].sym),
4354                              SYMBOL_LINKAGE_NAME (syms[j].sym)) == 0
4355                   && SYMBOL_CLASS (syms[i].sym) == SYMBOL_CLASS (syms[j].sym)
4356                   && SYMBOL_VALUE_ADDRESS (syms[i].sym)
4357                   == SYMBOL_VALUE_ADDRESS (syms[j].sym))
4358                 remove = 1;
4359             }
4360         }
4361       
4362       if (remove)
4363         {
4364           for (j = i + 1; j < nsyms; j += 1)
4365             syms[j - 1] = syms[j];
4366           nsyms -= 1;
4367         }
4368
4369       i += 1;
4370     }
4371   return nsyms;
4372 }
4373
4374 /* Given a type that corresponds to a renaming entity, use the type name
4375    to extract the scope (package name or function name, fully qualified,
4376    and following the GNAT encoding convention) where this renaming has been
4377    defined.  The string returned needs to be deallocated after use.  */
4378
4379 static char *
4380 xget_renaming_scope (struct type *renaming_type)
4381 {
4382   /* The renaming types adhere to the following convention:
4383      <scope>__<rename>___<XR extension>. 
4384      So, to extract the scope, we search for the "___XR" extension,
4385      and then backtrack until we find the first "__".  */
4386
4387   const char *name = type_name_no_tag (renaming_type);
4388   char *suffix = strstr (name, "___XR");
4389   char *last;
4390   int scope_len;
4391   char *scope;
4392
4393   /* Now, backtrack a bit until we find the first "__".  Start looking
4394      at suffix - 3, as the <rename> part is at least one character long.  */
4395
4396   for (last = suffix - 3; last > name; last--)
4397     if (last[0] == '_' && last[1] == '_')
4398       break;
4399
4400   /* Make a copy of scope and return it.  */
4401
4402   scope_len = last - name;
4403   scope = (char *) xmalloc ((scope_len + 1) * sizeof (char));
4404
4405   strncpy (scope, name, scope_len);
4406   scope[scope_len] = '\0';
4407
4408   return scope;
4409 }
4410
4411 /* Return nonzero if NAME corresponds to a package name.  */
4412
4413 static int
4414 is_package_name (const char *name)
4415 {
4416   /* Here, We take advantage of the fact that no symbols are generated
4417      for packages, while symbols are generated for each function.
4418      So the condition for NAME represent a package becomes equivalent
4419      to NAME not existing in our list of symbols.  There is only one
4420      small complication with library-level functions (see below).  */
4421
4422   char *fun_name;
4423
4424   /* If it is a function that has not been defined at library level,
4425      then we should be able to look it up in the symbols.  */
4426   if (standard_lookup (name, NULL, VAR_DOMAIN) != NULL)
4427     return 0;
4428
4429   /* Library-level function names start with "_ada_".  See if function
4430      "_ada_" followed by NAME can be found.  */
4431
4432   /* Do a quick check that NAME does not contain "__", since library-level
4433      functions names cannot contain "__" in them.  */
4434   if (strstr (name, "__") != NULL)
4435     return 0;
4436
4437   fun_name = xstrprintf ("_ada_%s", name);
4438
4439   return (standard_lookup (fun_name, NULL, VAR_DOMAIN) == NULL);
4440 }
4441
4442 /* Return nonzero if SYM corresponds to a renaming entity that is
4443    not visible from FUNCTION_NAME.  */
4444
4445 static int
4446 old_renaming_is_invisible (const struct symbol *sym, char *function_name)
4447 {
4448   char *scope;
4449
4450   if (SYMBOL_CLASS (sym) != LOC_TYPEDEF)
4451     return 0;
4452
4453   scope = xget_renaming_scope (SYMBOL_TYPE (sym));
4454
4455   make_cleanup (xfree, scope);
4456
4457   /* If the rename has been defined in a package, then it is visible.  */
4458   if (is_package_name (scope))
4459     return 0;
4460
4461   /* Check that the rename is in the current function scope by checking
4462      that its name starts with SCOPE.  */
4463
4464   /* If the function name starts with "_ada_", it means that it is
4465      a library-level function.  Strip this prefix before doing the
4466      comparison, as the encoding for the renaming does not contain
4467      this prefix.  */
4468   if (strncmp (function_name, "_ada_", 5) == 0)
4469     function_name += 5;
4470
4471   return (strncmp (function_name, scope, strlen (scope)) != 0);
4472 }
4473
4474 /* Remove entries from SYMS that corresponds to a renaming entity that
4475    is not visible from the function associated with CURRENT_BLOCK or
4476    that is superfluous due to the presence of more specific renaming
4477    information.  Places surviving symbols in the initial entries of
4478    SYMS and returns the number of surviving symbols.
4479    
4480    Rationale:
4481    First, in cases where an object renaming is implemented as a
4482    reference variable, GNAT may produce both the actual reference
4483    variable and the renaming encoding.  In this case, we discard the
4484    latter.
4485
4486    Second, GNAT emits a type following a specified encoding for each renaming
4487    entity.  Unfortunately, STABS currently does not support the definition
4488    of types that are local to a given lexical block, so all renamings types
4489    are emitted at library level.  As a consequence, if an application
4490    contains two renaming entities using the same name, and a user tries to
4491    print the value of one of these entities, the result of the ada symbol
4492    lookup will also contain the wrong renaming type.
4493
4494    This function partially covers for this limitation by attempting to
4495    remove from the SYMS list renaming symbols that should be visible
4496    from CURRENT_BLOCK.  However, there does not seem be a 100% reliable
4497    method with the current information available.  The implementation
4498    below has a couple of limitations (FIXME: brobecker-2003-05-12):  
4499    
4500       - When the user tries to print a rename in a function while there
4501         is another rename entity defined in a package:  Normally, the
4502         rename in the function has precedence over the rename in the
4503         package, so the latter should be removed from the list.  This is
4504         currently not the case.
4505         
4506       - This function will incorrectly remove valid renames if
4507         the CURRENT_BLOCK corresponds to a function which symbol name
4508         has been changed by an "Export" pragma.  As a consequence,
4509         the user will be unable to print such rename entities.  */
4510
4511 static int
4512 remove_irrelevant_renamings (struct ada_symbol_info *syms,
4513                              int nsyms, const struct block *current_block)
4514 {
4515   struct symbol *current_function;
4516   char *current_function_name;
4517   int i;
4518   int is_new_style_renaming;
4519
4520   /* If there is both a renaming foo___XR... encoded as a variable and
4521      a simple variable foo in the same block, discard the latter.
4522      First, zero out such symbols, then compress. */
4523   is_new_style_renaming = 0;
4524   for (i = 0; i < nsyms; i += 1)
4525     {
4526       struct symbol *sym = syms[i].sym;
4527       struct block *block = syms[i].block;
4528       const char *name;
4529       const char *suffix;
4530
4531       if (sym == NULL || SYMBOL_CLASS (sym) == LOC_TYPEDEF)
4532         continue;
4533       name = SYMBOL_LINKAGE_NAME (sym);
4534       suffix = strstr (name, "___XR");
4535
4536       if (suffix != NULL)
4537         {
4538           int name_len = suffix - name;
4539           int j;
4540           is_new_style_renaming = 1;
4541           for (j = 0; j < nsyms; j += 1)
4542             if (i != j && syms[j].sym != NULL
4543                 && strncmp (name, SYMBOL_LINKAGE_NAME (syms[j].sym),
4544                             name_len) == 0
4545                 && block == syms[j].block)
4546               syms[j].sym = NULL;
4547         }
4548     }
4549   if (is_new_style_renaming)
4550     {
4551       int j, k;
4552
4553       for (j = k = 0; j < nsyms; j += 1)
4554         if (syms[j].sym != NULL)
4555             {
4556               syms[k] = syms[j];
4557               k += 1;
4558             }
4559       return k;
4560     }
4561
4562   /* Extract the function name associated to CURRENT_BLOCK.
4563      Abort if unable to do so.  */
4564
4565   if (current_block == NULL)
4566     return nsyms;
4567
4568   current_function = block_linkage_function (current_block);
4569   if (current_function == NULL)
4570     return nsyms;
4571
4572   current_function_name = SYMBOL_LINKAGE_NAME (current_function);
4573   if (current_function_name == NULL)
4574     return nsyms;
4575
4576   /* Check each of the symbols, and remove it from the list if it is
4577      a type corresponding to a renaming that is out of the scope of
4578      the current block.  */
4579
4580   i = 0;
4581   while (i < nsyms)
4582     {
4583       if (ada_parse_renaming (syms[i].sym, NULL, NULL, NULL)
4584           == ADA_OBJECT_RENAMING
4585           && old_renaming_is_invisible (syms[i].sym, current_function_name))
4586         {
4587           int j;
4588           for (j = i + 1; j < nsyms; j += 1)
4589             syms[j - 1] = syms[j];
4590           nsyms -= 1;
4591         }
4592       else
4593         i += 1;
4594     }
4595
4596   return nsyms;
4597 }
4598
4599 /* Add to OBSTACKP all symbols from BLOCK (and its super-blocks)
4600    whose name and domain match NAME and DOMAIN respectively.
4601    If no match was found, then extend the search to "enclosing"
4602    routines (in other words, if we're inside a nested function,
4603    search the symbols defined inside the enclosing functions).
4604
4605    Note: This function assumes that OBSTACKP has 0 (zero) element in it.  */
4606
4607 static void
4608 ada_add_local_symbols (struct obstack *obstackp, const char *name,
4609                        struct block *block, domain_enum domain,
4610                        int wild_match)
4611 {
4612   int block_depth = 0;
4613
4614   while (block != NULL)
4615     {
4616       block_depth += 1;
4617       ada_add_block_symbols (obstackp, block, name, domain, NULL, wild_match);
4618
4619       /* If we found a non-function match, assume that's the one.  */
4620       if (is_nonfunction (defns_collected (obstackp, 0),
4621                           num_defns_collected (obstackp)))
4622         return;
4623
4624       block = BLOCK_SUPERBLOCK (block);
4625     }
4626
4627   /* If no luck so far, try to find NAME as a local symbol in some lexically
4628      enclosing subprogram.  */
4629   if (num_defns_collected (obstackp) == 0 && block_depth > 2)
4630     add_symbols_from_enclosing_procs (obstackp, name, domain, wild_match);
4631 }
4632
4633 /* Add to OBSTACKP all non-local symbols whose name and domain match
4634    NAME and DOMAIN respectively.  The search is performed on GLOBAL_BLOCK
4635    symbols if GLOBAL is non-zero, or on STATIC_BLOCK symbols otherwise.  */
4636
4637 static void
4638 ada_add_non_local_symbols (struct obstack *obstackp, const char *name,
4639                            domain_enum domain, int global,
4640                            int wild_match)
4641 {
4642   struct objfile *objfile;
4643   struct partial_symtab *ps;
4644
4645   ALL_PSYMTABS (objfile, ps)
4646   {
4647     QUIT;
4648     if (ps->readin
4649         || ada_lookup_partial_symbol (ps, name, global, domain, wild_match))
4650       {
4651         struct symtab *s = PSYMTAB_TO_SYMTAB (ps);
4652         const int block_kind = global ? GLOBAL_BLOCK : STATIC_BLOCK;
4653
4654         if (s == NULL || !s->primary)
4655           continue;
4656         ada_add_block_symbols (obstackp,
4657                                BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), block_kind),
4658                                name, domain, objfile, wild_match);
4659       }
4660   }
4661 }
4662
4663 /* Find symbols in DOMAIN matching NAME0, in BLOCK0 and enclosing
4664    scope and in global scopes, returning the number of matches.  Sets
4665    *RESULTS to point to a vector of (SYM,BLOCK) tuples,
4666    indicating the symbols found and the blocks and symbol tables (if
4667    any) in which they were found.  This vector are transient---good only to 
4668    the next call of ada_lookup_symbol_list.  Any non-function/non-enumeral 
4669    symbol match within the nest of blocks whose innermost member is BLOCK0,
4670    is the one match returned (no other matches in that or
4671      enclosing blocks is returned).  If there are any matches in or
4672    surrounding BLOCK0, then these alone are returned.  Otherwise, the
4673    search extends to global and file-scope (static) symbol tables.
4674    Names prefixed with "standard__" are handled specially: "standard__" 
4675    is first stripped off, and only static and global symbols are searched.  */
4676
4677 int
4678 ada_lookup_symbol_list (const char *name0, const struct block *block0,
4679                         domain_enum namespace,
4680                         struct ada_symbol_info **results)
4681 {
4682   struct symbol *sym;
4683   struct block *block;
4684   const char *name;
4685   int wild_match;
4686   int cacheIfUnique;
4687   int ndefns;
4688
4689   obstack_free (&symbol_list_obstack, NULL);
4690   obstack_init (&symbol_list_obstack);
4691
4692   cacheIfUnique = 0;
4693
4694   /* Search specified block and its superiors.  */
4695
4696   wild_match = (strstr (name0, "__") == NULL);
4697   name = name0;
4698   block = (struct block *) block0;      /* FIXME: No cast ought to be
4699                                            needed, but adding const will
4700                                            have a cascade effect.  */
4701
4702   /* Special case: If the user specifies a symbol name inside package
4703      Standard, do a non-wild matching of the symbol name without
4704      the "standard__" prefix.  This was primarily introduced in order
4705      to allow the user to specifically access the standard exceptions
4706      using, for instance, Standard.Constraint_Error when Constraint_Error
4707      is ambiguous (due to the user defining its own Constraint_Error
4708      entity inside its program).  */
4709   if (strncmp (name0, "standard__", sizeof ("standard__") - 1) == 0)
4710     {
4711       wild_match = 0;
4712       block = NULL;
4713       name = name0 + sizeof ("standard__") - 1;
4714     }
4715
4716   /* Check the non-global symbols.  If we have ANY match, then we're done.  */
4717
4718   ada_add_local_symbols (&symbol_list_obstack, name, block, namespace,
4719                          wild_match);
4720   if (num_defns_collected (&symbol_list_obstack) > 0)
4721     goto done;
4722
4723   /* No non-global symbols found.  Check our cache to see if we have
4724      already performed this search before.  If we have, then return
4725      the same result.  */
4726
4727   cacheIfUnique = 1;
4728   if (lookup_cached_symbol (name0, namespace, &sym, &block))
4729     {
4730       if (sym != NULL)
4731         add_defn_to_vec (&symbol_list_obstack, sym, block);
4732       goto done;
4733     }
4734
4735   /* Search symbols from all global blocks.  */
4736  
4737   ada_add_non_local_symbols (&symbol_list_obstack, name, namespace, 1,
4738                              wild_match);
4739
4740   /* Now add symbols from all per-file blocks if we've gotten no hits
4741      (not strictly correct, but perhaps better than an error).  */
4742
4743   if (num_defns_collected (&symbol_list_obstack) == 0)
4744     ada_add_non_local_symbols (&symbol_list_obstack, name, namespace, 0,
4745                                wild_match);
4746
4747 done:
4748   ndefns = num_defns_collected (&symbol_list_obstack);
4749   *results = defns_collected (&symbol_list_obstack, 1);
4750
4751   ndefns = remove_extra_symbols (*results, ndefns);
4752
4753   if (ndefns == 0)
4754     cache_symbol (name0, namespace, NULL, NULL);
4755
4756   if (ndefns == 1 && cacheIfUnique)
4757     cache_symbol (name0, namespace, (*results)[0].sym, (*results)[0].block);
4758
4759   ndefns = remove_irrelevant_renamings (*results, ndefns, block0);
4760
4761   return ndefns;
4762 }
4763
4764 struct symbol *
4765 ada_lookup_encoded_symbol (const char *name, const struct block *block0,
4766                            domain_enum namespace, struct block **block_found)
4767 {
4768   struct ada_symbol_info *candidates;
4769   int n_candidates;
4770
4771   n_candidates = ada_lookup_symbol_list (name, block0, namespace, &candidates);
4772
4773   if (n_candidates == 0)
4774     return NULL;
4775
4776   if (block_found != NULL)
4777     *block_found = candidates[0].block;
4778
4779   return fixup_symbol_section (candidates[0].sym, NULL);
4780 }  
4781
4782 /* Return a symbol in DOMAIN matching NAME, in BLOCK0 and enclosing
4783    scope and in global scopes, or NULL if none.  NAME is folded and
4784    encoded first.  Otherwise, the result is as for ada_lookup_symbol_list,
4785    choosing the first symbol if there are multiple choices.  
4786    *IS_A_FIELD_OF_THIS is set to 0 and *SYMTAB is set to the symbol
4787    table in which the symbol was found (in both cases, these
4788    assignments occur only if the pointers are non-null).  */
4789 struct symbol *
4790 ada_lookup_symbol (const char *name, const struct block *block0,
4791                    domain_enum namespace, int *is_a_field_of_this)
4792 {
4793   if (is_a_field_of_this != NULL)
4794     *is_a_field_of_this = 0;
4795
4796   return
4797     ada_lookup_encoded_symbol (ada_encode (ada_fold_name (name)),
4798                                block0, namespace, NULL);
4799 }
4800
4801 static struct symbol *
4802 ada_lookup_symbol_nonlocal (const char *name,
4803                             const char *linkage_name,
4804                             const struct block *block,
4805                             const domain_enum domain)
4806 {
4807   if (linkage_name == NULL)
4808     linkage_name = name;
4809   return ada_lookup_symbol (linkage_name, block_static_block (block), domain,
4810                             NULL);
4811 }
4812
4813
4814 /* True iff STR is a possible encoded suffix of a normal Ada name
4815    that is to be ignored for matching purposes.  Suffixes of parallel
4816    names (e.g., XVE) are not included here.  Currently, the possible suffixes
4817    are given by any of the regular expressions:
4818
4819    [.$][0-9]+       [nested subprogram suffix, on platforms such as GNU/Linux]
4820    ___[0-9]+        [nested subprogram suffix, on platforms such as HP/UX]
4821    _E[0-9]+[bs]$    [protected object entry suffixes]
4822    (X[nb]*)?((\$|__)[0-9](_?[0-9]+)|___(JM|LJM|X([FDBUP].*|R[^T]?)))?$
4823
4824    Also, any leading "__[0-9]+" sequence is skipped before the suffix
4825    match is performed.  This sequence is used to differentiate homonyms,
4826    is an optional part of a valid name suffix.  */
4827
4828 static int
4829 is_name_suffix (const char *str)
4830 {
4831   int k;
4832   const char *matching;
4833   const int len = strlen (str);
4834
4835   /* Skip optional leading __[0-9]+.  */
4836
4837   if (len > 3 && str[0] == '_' && str[1] == '_' && isdigit (str[2]))
4838     {
4839       str += 3;
4840       while (isdigit (str[0]))
4841         str += 1;
4842     }
4843   
4844   /* [.$][0-9]+ */
4845
4846   if (str[0] == '.' || str[0] == '$')
4847     {
4848       matching = str + 1;
4849       while (isdigit (matching[0]))
4850         matching += 1;
4851       if (matching[0] == '\0')
4852         return 1;
4853     }
4854
4855   /* ___[0-9]+ */
4856
4857   if (len > 3 && str[0] == '_' && str[1] == '_' && str[2] == '_')
4858     {
4859       matching = str + 3;
4860       while (isdigit (matching[0]))
4861         matching += 1;
4862       if (matching[0] == '\0')
4863         return 1;
4864     }
4865
4866 #if 0
4867   /* FIXME: brobecker/2005-09-23: Protected Object subprograms end
4868      with a N at the end. Unfortunately, the compiler uses the same
4869      convention for other internal types it creates. So treating
4870      all entity names that end with an "N" as a name suffix causes
4871      some regressions. For instance, consider the case of an enumerated
4872      type. To support the 'Image attribute, it creates an array whose
4873      name ends with N.
4874      Having a single character like this as a suffix carrying some
4875      information is a bit risky. Perhaps we should change the encoding
4876      to be something like "_N" instead.  In the meantime, do not do
4877      the following check.  */
4878   /* Protected Object Subprograms */
4879   if (len == 1 && str [0] == 'N')
4880     return 1;
4881 #endif
4882
4883   /* _E[0-9]+[bs]$ */
4884   if (len > 3 && str[0] == '_' && str [1] == 'E' && isdigit (str[2]))
4885     {
4886       matching = str + 3;
4887       while (isdigit (matching[0]))
4888         matching += 1;
4889       if ((matching[0] == 'b' || matching[0] == 's')
4890           && matching [1] == '\0')
4891         return 1;
4892     }
4893
4894   /* ??? We should not modify STR directly, as we are doing below.  This
4895      is fine in this case, but may become problematic later if we find
4896      that this alternative did not work, and want to try matching
4897      another one from the begining of STR.  Since we modified it, we
4898      won't be able to find the begining of the string anymore!  */
4899   if (str[0] == 'X')
4900     {
4901       str += 1;
4902       while (str[0] != '_' && str[0] != '\0')
4903         {
4904           if (str[0] != 'n' && str[0] != 'b')
4905             return 0;
4906           str += 1;
4907         }
4908     }
4909
4910   if (str[0] == '\000')
4911     return 1;
4912
4913   if (str[0] == '_')
4914     {
4915       if (str[1] != '_' || str[2] == '\000')
4916         return 0;
4917       if (str[2] == '_')
4918         {
4919           if (strcmp (str + 3, "JM") == 0)
4920             return 1;
4921           /* FIXME: brobecker/2004-09-30: GNAT will soon stop using
4922              the LJM suffix in favor of the JM one.  But we will
4923              still accept LJM as a valid suffix for a reasonable
4924              amount of time, just to allow ourselves to debug programs
4925              compiled using an older version of GNAT.  */
4926           if (strcmp (str + 3, "LJM") == 0)
4927             return 1;
4928           if (str[3] != 'X')
4929             return 0;
4930           if (str[4] == 'F' || str[4] == 'D' || str[4] == 'B'
4931               || str[4] == 'U' || str[4] == 'P')
4932             return 1;
4933           if (str[4] == 'R' && str[5] != 'T')
4934             return 1;
4935           return 0;
4936         }
4937       if (!isdigit (str[2]))
4938         return 0;
4939       for (k = 3; str[k] != '\0'; k += 1)
4940         if (!isdigit (str[k]) && str[k] != '_')
4941           return 0;
4942       return 1;
4943     }
4944   if (str[0] == '$' && isdigit (str[1]))
4945     {
4946       for (k = 2; str[k] != '\0'; k += 1)
4947         if (!isdigit (str[k]) && str[k] != '_')
4948           return 0;
4949       return 1;
4950     }
4951   return 0;
4952 }
4953
4954 /* Return non-zero if the string starting at NAME and ending before
4955    NAME_END contains no capital letters.  */
4956
4957 static int
4958 is_valid_name_for_wild_match (const char *name0)
4959 {
4960   const char *decoded_name = ada_decode (name0);
4961   int i;
4962
4963   /* If the decoded name starts with an angle bracket, it means that
4964      NAME0 does not follow the GNAT encoding format.  It should then
4965      not be allowed as a possible wild match.  */
4966   if (decoded_name[0] == '<')
4967     return 0;
4968
4969   for (i=0; decoded_name[i] != '\0'; i++)
4970     if (isalpha (decoded_name[i]) && !islower (decoded_name[i]))
4971       return 0;
4972
4973   return 1;
4974 }
4975
4976 /* True if NAME represents a name of the form A1.A2....An, n>=1 and
4977    PATN[0..PATN_LEN-1] = Ak.Ak+1.....An for some k >= 1.  Ignores
4978    informational suffixes of NAME (i.e., for which is_name_suffix is
4979    true).  */
4980
4981 static int
4982 wild_match (const char *patn0, int patn_len, const char *name0)
4983 {
4984   char* match;
4985   const char* start;
4986   start = name0;
4987   while (1)
4988     {
4989       match = strstr (start, patn0);
4990       if (match == NULL)
4991         return 0;
4992       if ((match == name0 
4993            || match[-1] == '.' 
4994            || (match > name0 + 1 && match[-1] == '_' && match[-2] == '_')
4995            || (match == name0 + 5 && strncmp ("_ada_", name0, 5) == 0))
4996           && is_name_suffix (match + patn_len))
4997         return (match == name0 || is_valid_name_for_wild_match (name0));
4998       start = match + 1;
4999     }
5000 }
5001
5002
5003 /* Add symbols from BLOCK matching identifier NAME in DOMAIN to
5004    vector *defn_symbols, updating the list of symbols in OBSTACKP 
5005    (if necessary).  If WILD, treat as NAME with a wildcard prefix. 
5006    OBJFILE is the section containing BLOCK.
5007    SYMTAB is recorded with each symbol added.  */
5008
5009 static void
5010 ada_add_block_symbols (struct obstack *obstackp,
5011                        struct block *block, const char *name,
5012                        domain_enum domain, struct objfile *objfile,
5013                        int wild)
5014 {
5015   struct dict_iterator iter;
5016   int name_len = strlen (name);
5017   /* A matching argument symbol, if any.  */
5018   struct symbol *arg_sym;
5019   /* Set true when we find a matching non-argument symbol.  */
5020   int found_sym;
5021   struct symbol *sym;
5022
5023   arg_sym = NULL;
5024   found_sym = 0;
5025   if (wild)
5026     {
5027       struct symbol *sym;
5028       ALL_BLOCK_SYMBOLS (block, iter, sym)
5029       {
5030         if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
5031                                    SYMBOL_DOMAIN (sym), domain)
5032             && wild_match (name, name_len, SYMBOL_LINKAGE_NAME (sym)))
5033           {
5034             if (SYMBOL_CLASS (sym) == LOC_UNRESOLVED)
5035               continue;
5036             else if (SYMBOL_IS_ARGUMENT (sym))
5037               arg_sym = sym;
5038             else
5039               {
5040                 found_sym = 1;
5041                 add_defn_to_vec (obstackp,
5042                                  fixup_symbol_section (sym, objfile),
5043                                  block);
5044               }
5045           }
5046       }
5047     }
5048   else
5049     {
5050       ALL_BLOCK_SYMBOLS (block, iter, sym)
5051       {
5052         if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
5053                                    SYMBOL_DOMAIN (sym), domain))
5054           {
5055             int cmp = strncmp (name, SYMBOL_LINKAGE_NAME (sym), name_len);
5056             if (cmp == 0
5057                 && is_name_suffix (SYMBOL_LINKAGE_NAME (sym) + name_len))
5058               {
5059                 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
5060                   {
5061                     if (SYMBOL_IS_ARGUMENT (sym))
5062                       arg_sym = sym;
5063                     else
5064                       {
5065                         found_sym = 1;
5066                         add_defn_to_vec (obstackp,
5067                                          fixup_symbol_section (sym, objfile),
5068                                          block);
5069                       }
5070                   }
5071               }
5072           }
5073       }
5074     }
5075
5076   if (!found_sym && arg_sym != NULL)
5077     {
5078       add_defn_to_vec (obstackp,
5079                        fixup_symbol_section (arg_sym, objfile),
5080                        block);
5081     }
5082
5083   if (!wild)
5084     {
5085       arg_sym = NULL;
5086       found_sym = 0;
5087
5088       ALL_BLOCK_SYMBOLS (block, iter, sym)
5089       {
5090         if (symbol_matches_domain (SYMBOL_LANGUAGE (sym),
5091                                    SYMBOL_DOMAIN (sym), domain))
5092           {
5093             int cmp;
5094
5095             cmp = (int) '_' - (int) SYMBOL_LINKAGE_NAME (sym)[0];
5096             if (cmp == 0)
5097               {
5098                 cmp = strncmp ("_ada_", SYMBOL_LINKAGE_NAME (sym), 5);
5099                 if (cmp == 0)
5100                   cmp = strncmp (name, SYMBOL_LINKAGE_NAME (sym) + 5,
5101                                  name_len);
5102               }
5103
5104             if (cmp == 0
5105                 && is_name_suffix (SYMBOL_LINKAGE_NAME (sym) + name_len + 5))
5106               {
5107                 if (SYMBOL_CLASS (sym) != LOC_UNRESOLVED)
5108                   {
5109                     if (SYMBOL_IS_ARGUMENT (sym))
5110                       arg_sym = sym;
5111                     else
5112                       {
5113                         found_sym = 1;
5114                         add_defn_to_vec (obstackp,
5115                                          fixup_symbol_section (sym, objfile),
5116                                          block);
5117                       }
5118                   }
5119               }
5120           }
5121       }
5122
5123       /* NOTE: This really shouldn't be needed for _ada_ symbols.
5124          They aren't parameters, right?  */
5125       if (!found_sym && arg_sym != NULL)
5126         {
5127           add_defn_to_vec (obstackp,
5128                            fixup_symbol_section (arg_sym, objfile),
5129                            block);
5130         }
5131     }
5132 }
5133 \f
5134
5135                                 /* Symbol Completion */
5136
5137 /* If SYM_NAME is a completion candidate for TEXT, return this symbol
5138    name in a form that's appropriate for the completion.  The result
5139    does not need to be deallocated, but is only good until the next call.
5140
5141    TEXT_LEN is equal to the length of TEXT.
5142    Perform a wild match if WILD_MATCH is set.
5143    ENCODED should be set if TEXT represents the start of a symbol name
5144    in its encoded form.  */
5145
5146 static const char *
5147 symbol_completion_match (const char *sym_name,
5148                          const char *text, int text_len,
5149                          int wild_match, int encoded)
5150 {
5151   char *result;
5152   const int verbatim_match = (text[0] == '<');
5153   int match = 0;
5154
5155   if (verbatim_match)
5156     {
5157       /* Strip the leading angle bracket.  */
5158       text = text + 1;
5159       text_len--;
5160     }
5161
5162   /* First, test against the fully qualified name of the symbol.  */
5163
5164   if (strncmp (sym_name, text, text_len) == 0)
5165     match = 1;
5166
5167   if (match && !encoded)
5168     {
5169       /* One needed check before declaring a positive match is to verify
5170          that iff we are doing a verbatim match, the decoded version
5171          of the symbol name starts with '<'.  Otherwise, this symbol name
5172          is not a suitable completion.  */
5173       const char *sym_name_copy = sym_name;
5174       int has_angle_bracket;
5175
5176       sym_name = ada_decode (sym_name);
5177       has_angle_bracket = (sym_name[0] == '<');
5178       match = (has_angle_bracket == verbatim_match);
5179       sym_name = sym_name_copy;
5180     }
5181
5182   if (match && !verbatim_match)
5183     {
5184       /* When doing non-verbatim match, another check that needs to
5185          be done is to verify that the potentially matching symbol name
5186          does not include capital letters, because the ada-mode would
5187          not be able to understand these symbol names without the
5188          angle bracket notation.  */
5189       const char *tmp;
5190
5191       for (tmp = sym_name; *tmp != '\0' && !isupper (*tmp); tmp++);
5192       if (*tmp != '\0')
5193         match = 0;
5194     }
5195
5196   /* Second: Try wild matching...  */
5197
5198   if (!match && wild_match)
5199     {
5200       /* Since we are doing wild matching, this means that TEXT
5201          may represent an unqualified symbol name.  We therefore must
5202          also compare TEXT against the unqualified name of the symbol.  */
5203       sym_name = ada_unqualified_name (ada_decode (sym_name));
5204
5205       if (strncmp (sym_name, text, text_len) == 0)
5206         match = 1;
5207     }
5208
5209   /* Finally: If we found a mach, prepare the result to return.  */
5210
5211   if (!match)
5212     return NULL;
5213
5214   if (verbatim_match)
5215     sym_name = add_angle_brackets (sym_name);
5216
5217   if (!encoded)
5218     sym_name = ada_decode (sym_name);
5219
5220   return sym_name;
5221 }
5222
5223 typedef char *char_ptr;
5224 DEF_VEC_P (char_ptr);
5225
5226 /* A companion function to ada_make_symbol_completion_list().
5227    Check if SYM_NAME represents a symbol which name would be suitable
5228    to complete TEXT (TEXT_LEN is the length of TEXT), in which case
5229    it is appended at the end of the given string vector SV.
5230
5231    ORIG_TEXT is the string original string from the user command
5232    that needs to be completed.  WORD is the entire command on which
5233    completion should be performed.  These two parameters are used to
5234    determine which part of the symbol name should be added to the
5235    completion vector.
5236    if WILD_MATCH is set, then wild matching is performed.
5237    ENCODED should be set if TEXT represents a symbol name in its
5238    encoded formed (in which case the completion should also be
5239    encoded).  */
5240
5241 static void
5242 symbol_completion_add (VEC(char_ptr) **sv,
5243                        const char *sym_name,
5244                        const char *text, int text_len,
5245                        const char *orig_text, const char *word,
5246                        int wild_match, int encoded)
5247 {
5248   const char *match = symbol_completion_match (sym_name, text, text_len,
5249                                                wild_match, encoded);
5250   char *completion;
5251
5252   if (match == NULL)
5253     return;
5254
5255   /* We found a match, so add the appropriate completion to the given
5256      string vector.  */
5257
5258   if (word == orig_text)
5259     {
5260       completion = xmalloc (strlen (match) + 5);
5261       strcpy (completion, match);
5262     }
5263   else if (word > orig_text)
5264     {
5265       /* Return some portion of sym_name.  */
5266       completion = xmalloc (strlen (match) + 5);
5267       strcpy (completion, match + (word - orig_text));
5268     }
5269   else
5270     {
5271       /* Return some of ORIG_TEXT plus sym_name.  */
5272       completion = xmalloc (strlen (match) + (orig_text - word) + 5);
5273       strncpy (completion, word, orig_text - word);
5274       completion[orig_text - word] = '\0';
5275       strcat (completion, match);
5276     }
5277
5278   VEC_safe_push (char_ptr, *sv, completion);
5279 }
5280
5281 /* Return a list of possible symbol names completing TEXT0.  The list
5282    is NULL terminated.  WORD is the entire command on which completion
5283    is made.  */
5284
5285 static char **
5286 ada_make_symbol_completion_list (char *text0, char *word)
5287 {
5288   char *text;
5289   int text_len;
5290   int wild_match;
5291   int encoded;
5292   VEC(char_ptr) *completions = VEC_alloc (char_ptr, 128);
5293   struct symbol *sym;
5294   struct symtab *s;
5295   struct partial_symtab *ps;
5296   struct minimal_symbol *msymbol;
5297   struct objfile *objfile;
5298   struct block *b, *surrounding_static_block = 0;
5299   int i;
5300   struct dict_iterator iter;
5301
5302   if (text0[0] == '<')
5303     {
5304       text = xstrdup (text0);
5305       make_cleanup (xfree, text);
5306       text_len = strlen (text);
5307       wild_match = 0;
5308       encoded = 1;
5309     }
5310   else
5311     {
5312       text = xstrdup (ada_encode (text0));
5313       make_cleanup (xfree, text);
5314       text_len = strlen (text);
5315       for (i = 0; i < text_len; i++)
5316         text[i] = tolower (text[i]);
5317
5318       encoded = (strstr (text0, "__") != NULL);
5319       /* If the name contains a ".", then the user is entering a fully
5320          qualified entity name, and the match must not be done in wild
5321          mode.  Similarly, if the user wants to complete what looks like
5322          an encoded name, the match must not be done in wild mode.  */
5323       wild_match = (strchr (text0, '.') == NULL && !encoded);
5324     }
5325
5326   /* First, look at the partial symtab symbols.  */
5327   ALL_PSYMTABS (objfile, ps)
5328   {
5329     struct partial_symbol **psym;
5330
5331     /* If the psymtab's been read in we'll get it when we search
5332        through the blockvector.  */
5333     if (ps->readin)
5334       continue;
5335
5336     for (psym = objfile->global_psymbols.list + ps->globals_offset;
5337          psym < (objfile->global_psymbols.list + ps->globals_offset
5338                  + ps->n_global_syms); psym++)
5339       {
5340         QUIT;
5341         symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (*psym),
5342                                text, text_len, text0, word,
5343                                wild_match, encoded);
5344       }
5345
5346     for (psym = objfile->static_psymbols.list + ps->statics_offset;
5347          psym < (objfile->static_psymbols.list + ps->statics_offset
5348                  + ps->n_static_syms); psym++)
5349       {
5350         QUIT;
5351         symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (*psym),
5352                                text, text_len, text0, word,
5353                                wild_match, encoded);
5354       }
5355   }
5356
5357   /* At this point scan through the misc symbol vectors and add each
5358      symbol you find to the list.  Eventually we want to ignore
5359      anything that isn't a text symbol (everything else will be
5360      handled by the psymtab code above).  */
5361
5362   ALL_MSYMBOLS (objfile, msymbol)
5363   {
5364     QUIT;
5365     symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (msymbol),
5366                            text, text_len, text0, word, wild_match, encoded);
5367   }
5368
5369   /* Search upwards from currently selected frame (so that we can
5370      complete on local vars.  */
5371
5372   for (b = get_selected_block (0); b != NULL; b = BLOCK_SUPERBLOCK (b))
5373     {
5374       if (!BLOCK_SUPERBLOCK (b))
5375         surrounding_static_block = b;   /* For elmin of dups */
5376
5377       ALL_BLOCK_SYMBOLS (b, iter, sym)
5378       {
5379         symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (sym),
5380                                text, text_len, text0, word,
5381                                wild_match, encoded);
5382       }
5383     }
5384
5385   /* Go through the symtabs and check the externs and statics for
5386      symbols which match.  */
5387
5388   ALL_SYMTABS (objfile, s)
5389   {
5390     QUIT;
5391     b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), GLOBAL_BLOCK);
5392     ALL_BLOCK_SYMBOLS (b, iter, sym)
5393     {
5394       symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (sym),
5395                              text, text_len, text0, word,
5396                              wild_match, encoded);
5397     }
5398   }
5399
5400   ALL_SYMTABS (objfile, s)
5401   {
5402     QUIT;
5403     b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), STATIC_BLOCK);
5404     /* Don't do this block twice.  */
5405     if (b == surrounding_static_block)
5406       continue;
5407     ALL_BLOCK_SYMBOLS (b, iter, sym)
5408     {
5409       symbol_completion_add (&completions, SYMBOL_LINKAGE_NAME (sym),
5410                              text, text_len, text0, word,
5411                              wild_match, encoded);
5412     }
5413   }
5414
5415   /* Append the closing NULL entry.  */
5416   VEC_safe_push (char_ptr, completions, NULL);
5417
5418   /* Make a copy of the COMPLETIONS VEC before we free it, and then
5419      return the copy.  It's unfortunate that we have to make a copy
5420      of an array that we're about to destroy, but there is nothing much
5421      we can do about it.  Fortunately, it's typically not a very large
5422      array.  */
5423   {
5424     const size_t completions_size = 
5425       VEC_length (char_ptr, completions) * sizeof (char *);
5426     char **result = malloc (completions_size);
5427     
5428     memcpy (result, VEC_address (char_ptr, completions), completions_size);
5429
5430     VEC_free (char_ptr, completions);
5431     return result;
5432   }
5433 }
5434
5435                                 /* Field Access */
5436
5437 /* Return non-zero if TYPE is a pointer to the GNAT dispatch table used
5438    for tagged types.  */
5439
5440 static int
5441 ada_is_dispatch_table_ptr_type (struct type *type)
5442 {
5443   char *name;
5444
5445   if (TYPE_CODE (type) != TYPE_CODE_PTR)
5446     return 0;
5447
5448   name = TYPE_NAME (TYPE_TARGET_TYPE (type));
5449   if (name == NULL)
5450     return 0;
5451
5452   return (strcmp (name, "ada__tags__dispatch_table") == 0);
5453 }
5454
5455 /* True if field number FIELD_NUM in struct or union type TYPE is supposed
5456    to be invisible to users.  */
5457
5458 int
5459 ada_is_ignored_field (struct type *type, int field_num)
5460 {
5461   if (field_num < 0 || field_num > TYPE_NFIELDS (type))
5462     return 1;
5463    
5464   /* Check the name of that field.  */
5465   {
5466     const char *name = TYPE_FIELD_NAME (type, field_num);
5467
5468     /* Anonymous field names should not be printed.
5469        brobecker/2007-02-20: I don't think this can actually happen
5470        but we don't want to print the value of annonymous fields anyway.  */
5471     if (name == NULL)
5472       return 1;
5473
5474     /* A field named "_parent" is internally generated by GNAT for
5475        tagged types, and should not be printed either.  */
5476     if (name[0] == '_' && strncmp (name, "_parent", 7) != 0)
5477       return 1;
5478   }
5479
5480   /* If this is the dispatch table of a tagged type, then ignore.  */
5481   if (ada_is_tagged_type (type, 1)
5482       && ada_is_dispatch_table_ptr_type (TYPE_FIELD_TYPE (type, field_num)))
5483     return 1;
5484
5485   /* Not a special field, so it should not be ignored.  */
5486   return 0;
5487 }
5488
5489 /* True iff TYPE has a tag field.  If REFOK, then TYPE may also be a
5490    pointer or reference type whose ultimate target has a tag field. */
5491
5492 int
5493 ada_is_tagged_type (struct type *type, int refok)
5494 {
5495   return (ada_lookup_struct_elt_type (type, "_tag", refok, 1, NULL) != NULL);
5496 }
5497
5498 /* True iff TYPE represents the type of X'Tag */
5499
5500 int
5501 ada_is_tag_type (struct type *type)
5502 {
5503   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_PTR)
5504     return 0;
5505   else
5506     {
5507       const char *name = ada_type_name (TYPE_TARGET_TYPE (type));
5508       return (name != NULL
5509               && strcmp (name, "ada__tags__dispatch_table") == 0);
5510     }
5511 }
5512
5513 /* The type of the tag on VAL.  */
5514
5515 struct type *
5516 ada_tag_type (struct value *val)
5517 {
5518   return ada_lookup_struct_elt_type (value_type (val), "_tag", 1, 0, NULL);
5519 }
5520
5521 /* The value of the tag on VAL.  */
5522
5523 struct value *
5524 ada_value_tag (struct value *val)
5525 {
5526   return ada_value_struct_elt (val, "_tag", 0);
5527 }
5528
5529 /* The value of the tag on the object of type TYPE whose contents are
5530    saved at VALADDR, if it is non-null, or is at memory address
5531    ADDRESS. */
5532
5533 static struct value *
5534 value_tag_from_contents_and_address (struct type *type,
5535                                      const gdb_byte *valaddr,
5536                                      CORE_ADDR address)
5537 {
5538   int tag_byte_offset, dummy1, dummy2;
5539   struct type *tag_type;
5540   if (find_struct_field ("_tag", type, 0, &tag_type, &tag_byte_offset,
5541                          NULL, NULL, NULL))
5542     {
5543       const gdb_byte *valaddr1 = ((valaddr == NULL)
5544                                   ? NULL
5545                                   : valaddr + tag_byte_offset);
5546       CORE_ADDR address1 = (address == 0) ? 0 : address + tag_byte_offset;
5547
5548       return value_from_contents_and_address (tag_type, valaddr1, address1);
5549     }
5550   return NULL;
5551 }
5552
5553 static struct type *
5554 type_from_tag (struct value *tag)
5555 {
5556   const char *type_name = ada_tag_name (tag);
5557   if (type_name != NULL)
5558     return ada_find_any_type (ada_encode (type_name));
5559   return NULL;
5560 }
5561
5562 struct tag_args
5563 {
5564   struct value *tag;
5565   char *name;
5566 };
5567
5568
5569 static int ada_tag_name_1 (void *);
5570 static int ada_tag_name_2 (struct tag_args *);
5571
5572 /* Wrapper function used by ada_tag_name.  Given a struct tag_args*
5573    value ARGS, sets ARGS->name to the tag name of ARGS->tag.  
5574    The value stored in ARGS->name is valid until the next call to 
5575    ada_tag_name_1.  */
5576
5577 static int
5578 ada_tag_name_1 (void *args0)
5579 {
5580   struct tag_args *args = (struct tag_args *) args0;
5581   static char name[1024];
5582   char *p;
5583   struct value *val;
5584   args->name = NULL;
5585   val = ada_value_struct_elt (args->tag, "tsd", 1);
5586   if (val == NULL)
5587     return ada_tag_name_2 (args);
5588   val = ada_value_struct_elt (val, "expanded_name", 1);
5589   if (val == NULL)
5590     return 0;
5591   read_memory_string (value_as_address (val), name, sizeof (name) - 1);
5592   for (p = name; *p != '\0'; p += 1)
5593     if (isalpha (*p))
5594       *p = tolower (*p);
5595   args->name = name;
5596   return 0;
5597 }
5598
5599 /* Utility function for ada_tag_name_1 that tries the second
5600    representation for the dispatch table (in which there is no
5601    explicit 'tsd' field in the referent of the tag pointer, and instead
5602    the tsd pointer is stored just before the dispatch table. */
5603    
5604 static int
5605 ada_tag_name_2 (struct tag_args *args)
5606 {
5607   struct type *info_type;
5608   static char name[1024];
5609   char *p;
5610   struct value *val, *valp;
5611
5612   args->name = NULL;
5613   info_type = ada_find_any_type ("ada__tags__type_specific_data");
5614   if (info_type == NULL)
5615     return 0;
5616   info_type = lookup_pointer_type (lookup_pointer_type (info_type));
5617   valp = value_cast (info_type, args->tag);
5618   if (valp == NULL)
5619     return 0;
5620   val = value_ind (value_ptradd (valp,
5621                                  value_from_longest (builtin_type_int8, -1)));
5622   if (val == NULL)
5623     return 0;
5624   val = ada_value_struct_elt (val, "expanded_name", 1);
5625   if (val == NULL)
5626     return 0;
5627   read_memory_string (value_as_address (val), name, sizeof (name) - 1);
5628   for (p = name; *p != '\0'; p += 1)
5629     if (isalpha (*p))
5630       *p = tolower (*p);
5631   args->name = name;
5632   return 0;
5633 }
5634
5635 /* The type name of the dynamic type denoted by the 'tag value TAG, as
5636  * a C string.  */
5637
5638 const char *
5639 ada_tag_name (struct value *tag)
5640 {
5641   struct tag_args args;
5642   if (!ada_is_tag_type (value_type (tag)))
5643     return NULL;
5644   args.tag = tag;
5645   args.name = NULL;
5646   catch_errors (ada_tag_name_1, &args, NULL, RETURN_MASK_ALL);
5647   return args.name;
5648 }
5649
5650 /* The parent type of TYPE, or NULL if none.  */
5651
5652 struct type *
5653 ada_parent_type (struct type *type)
5654 {
5655   int i;
5656
5657   type = ada_check_typedef (type);
5658
5659   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
5660     return NULL;
5661
5662   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
5663     if (ada_is_parent_field (type, i))
5664       {
5665         struct type *parent_type = TYPE_FIELD_TYPE (type, i);
5666
5667         /* If the _parent field is a pointer, then dereference it.  */
5668         if (TYPE_CODE (parent_type) == TYPE_CODE_PTR)
5669           parent_type = TYPE_TARGET_TYPE (parent_type);
5670         /* If there is a parallel XVS type, get the actual base type.  */
5671         parent_type = ada_get_base_type (parent_type);
5672
5673         return ada_check_typedef (parent_type);
5674       }
5675
5676   return NULL;
5677 }
5678
5679 /* True iff field number FIELD_NUM of structure type TYPE contains the
5680    parent-type (inherited) fields of a derived type.  Assumes TYPE is
5681    a structure type with at least FIELD_NUM+1 fields.  */
5682
5683 int
5684 ada_is_parent_field (struct type *type, int field_num)
5685 {
5686   const char *name = TYPE_FIELD_NAME (ada_check_typedef (type), field_num);
5687   return (name != NULL
5688           && (strncmp (name, "PARENT", 6) == 0
5689               || strncmp (name, "_parent", 7) == 0));
5690 }
5691
5692 /* True iff field number FIELD_NUM of structure type TYPE is a
5693    transparent wrapper field (which should be silently traversed when doing
5694    field selection and flattened when printing).  Assumes TYPE is a
5695    structure type with at least FIELD_NUM+1 fields.  Such fields are always
5696    structures.  */
5697
5698 int
5699 ada_is_wrapper_field (struct type *type, int field_num)
5700 {
5701   const char *name = TYPE_FIELD_NAME (type, field_num);
5702   return (name != NULL
5703           && (strncmp (name, "PARENT", 6) == 0
5704               || strcmp (name, "REP") == 0
5705               || strncmp (name, "_parent", 7) == 0
5706               || name[0] == 'S' || name[0] == 'R' || name[0] == 'O'));
5707 }
5708
5709 /* True iff field number FIELD_NUM of structure or union type TYPE
5710    is a variant wrapper.  Assumes TYPE is a structure type with at least
5711    FIELD_NUM+1 fields.  */
5712
5713 int
5714 ada_is_variant_part (struct type *type, int field_num)
5715 {
5716   struct type *field_type = TYPE_FIELD_TYPE (type, field_num);
5717   return (TYPE_CODE (field_type) == TYPE_CODE_UNION
5718           || (is_dynamic_field (type, field_num)
5719               && (TYPE_CODE (TYPE_TARGET_TYPE (field_type)) 
5720                   == TYPE_CODE_UNION)));
5721 }
5722
5723 /* Assuming that VAR_TYPE is a variant wrapper (type of the variant part)
5724    whose discriminants are contained in the record type OUTER_TYPE,
5725    returns the type of the controlling discriminant for the variant.  */
5726
5727 struct type *
5728 ada_variant_discrim_type (struct type *var_type, struct type *outer_type)
5729 {
5730   char *name = ada_variant_discrim_name (var_type);
5731   struct type *type =
5732     ada_lookup_struct_elt_type (outer_type, name, 1, 1, NULL);
5733   if (type == NULL)
5734     return builtin_type_int32;
5735   else
5736     return type;
5737 }
5738
5739 /* Assuming that TYPE is the type of a variant wrapper, and FIELD_NUM is a
5740    valid field number within it, returns 1 iff field FIELD_NUM of TYPE
5741    represents a 'when others' clause; otherwise 0.  */
5742
5743 int
5744 ada_is_others_clause (struct type *type, int field_num)
5745 {
5746   const char *name = TYPE_FIELD_NAME (type, field_num);
5747   return (name != NULL && name[0] == 'O');
5748 }
5749
5750 /* Assuming that TYPE0 is the type of the variant part of a record,
5751    returns the name of the discriminant controlling the variant.
5752    The value is valid until the next call to ada_variant_discrim_name.  */
5753
5754 char *
5755 ada_variant_discrim_name (struct type *type0)
5756 {
5757   static char *result = NULL;
5758   static size_t result_len = 0;
5759   struct type *type;
5760   const char *name;
5761   const char *discrim_end;
5762   const char *discrim_start;
5763
5764   if (TYPE_CODE (type0) == TYPE_CODE_PTR)
5765     type = TYPE_TARGET_TYPE (type0);
5766   else
5767     type = type0;
5768
5769   name = ada_type_name (type);
5770
5771   if (name == NULL || name[0] == '\000')
5772     return "";
5773
5774   for (discrim_end = name + strlen (name) - 6; discrim_end != name;
5775        discrim_end -= 1)
5776     {
5777       if (strncmp (discrim_end, "___XVN", 6) == 0)
5778         break;
5779     }
5780   if (discrim_end == name)
5781     return "";
5782
5783   for (discrim_start = discrim_end; discrim_start != name + 3;
5784        discrim_start -= 1)
5785     {
5786       if (discrim_start == name + 1)
5787         return "";
5788       if ((discrim_start > name + 3
5789            && strncmp (discrim_start - 3, "___", 3) == 0)
5790           || discrim_start[-1] == '.')
5791         break;
5792     }
5793
5794   GROW_VECT (result, result_len, discrim_end - discrim_start + 1);
5795   strncpy (result, discrim_start, discrim_end - discrim_start);
5796   result[discrim_end - discrim_start] = '\0';
5797   return result;
5798 }
5799
5800 /* Scan STR for a subtype-encoded number, beginning at position K.
5801    Put the position of the character just past the number scanned in
5802    *NEW_K, if NEW_K!=NULL.  Put the scanned number in *R, if R!=NULL.
5803    Return 1 if there was a valid number at the given position, and 0
5804    otherwise.  A "subtype-encoded" number consists of the absolute value
5805    in decimal, followed by the letter 'm' to indicate a negative number.
5806    Assumes 0m does not occur.  */
5807
5808 int
5809 ada_scan_number (const char str[], int k, LONGEST * R, int *new_k)
5810 {
5811   ULONGEST RU;
5812
5813   if (!isdigit (str[k]))
5814     return 0;
5815
5816   /* Do it the hard way so as not to make any assumption about
5817      the relationship of unsigned long (%lu scan format code) and
5818      LONGEST.  */
5819   RU = 0;
5820   while (isdigit (str[k]))
5821     {
5822       RU = RU * 10 + (str[k] - '0');
5823       k += 1;
5824     }
5825
5826   if (str[k] == 'm')
5827     {
5828       if (R != NULL)
5829         *R = (-(LONGEST) (RU - 1)) - 1;
5830       k += 1;
5831     }
5832   else if (R != NULL)
5833     *R = (LONGEST) RU;
5834
5835   /* NOTE on the above: Technically, C does not say what the results of
5836      - (LONGEST) RU or (LONGEST) -RU are for RU == largest positive
5837      number representable as a LONGEST (although either would probably work
5838      in most implementations).  When RU>0, the locution in the then branch
5839      above is always equivalent to the negative of RU.  */
5840
5841   if (new_k != NULL)
5842     *new_k = k;
5843   return 1;
5844 }
5845
5846 /* Assuming that TYPE is a variant part wrapper type (a VARIANTS field),
5847    and FIELD_NUM is a valid field number within it, returns 1 iff VAL is
5848    in the range encoded by field FIELD_NUM of TYPE; otherwise 0.  */
5849
5850 int
5851 ada_in_variant (LONGEST val, struct type *type, int field_num)
5852 {
5853   const char *name = TYPE_FIELD_NAME (type, field_num);
5854   int p;
5855
5856   p = 0;
5857   while (1)
5858     {
5859       switch (name[p])
5860         {
5861         case '\0':
5862           return 0;
5863         case 'S':
5864           {
5865             LONGEST W;
5866             if (!ada_scan_number (name, p + 1, &W, &p))
5867               return 0;
5868             if (val == W)
5869               return 1;
5870             break;
5871           }
5872         case 'R':
5873           {
5874             LONGEST L, U;
5875             if (!ada_scan_number (name, p + 1, &L, &p)
5876                 || name[p] != 'T' || !ada_scan_number (name, p + 1, &U, &p))
5877               return 0;
5878             if (val >= L && val <= U)
5879               return 1;
5880             break;
5881           }
5882         case 'O':
5883           return 1;
5884         default:
5885           return 0;
5886         }
5887     }
5888 }
5889
5890 /* FIXME: Lots of redundancy below.  Try to consolidate. */
5891
5892 /* Given a value ARG1 (offset by OFFSET bytes) of a struct or union type
5893    ARG_TYPE, extract and return the value of one of its (non-static)
5894    fields.  FIELDNO says which field.   Differs from value_primitive_field
5895    only in that it can handle packed values of arbitrary type.  */
5896
5897 static struct value *
5898 ada_value_primitive_field (struct value *arg1, int offset, int fieldno,
5899                            struct type *arg_type)
5900 {
5901   struct type *type;
5902
5903   arg_type = ada_check_typedef (arg_type);
5904   type = TYPE_FIELD_TYPE (arg_type, fieldno);
5905
5906   /* Handle packed fields.  */
5907
5908   if (TYPE_FIELD_BITSIZE (arg_type, fieldno) != 0)
5909     {
5910       int bit_pos = TYPE_FIELD_BITPOS (arg_type, fieldno);
5911       int bit_size = TYPE_FIELD_BITSIZE (arg_type, fieldno);
5912
5913       return ada_value_primitive_packed_val (arg1, value_contents (arg1),
5914                                              offset + bit_pos / 8,
5915                                              bit_pos % 8, bit_size, type);
5916     }
5917   else
5918     return value_primitive_field (arg1, offset, fieldno, arg_type);
5919 }
5920
5921 /* Find field with name NAME in object of type TYPE.  If found, 
5922    set the following for each argument that is non-null:
5923     - *FIELD_TYPE_P to the field's type; 
5924     - *BYTE_OFFSET_P to OFFSET + the byte offset of the field within 
5925       an object of that type;
5926     - *BIT_OFFSET_P to the bit offset modulo byte size of the field; 
5927     - *BIT_SIZE_P to its size in bits if the field is packed, and 
5928       0 otherwise;
5929    If INDEX_P is non-null, increment *INDEX_P by the number of source-visible
5930    fields up to but not including the desired field, or by the total
5931    number of fields if not found.   A NULL value of NAME never
5932    matches; the function just counts visible fields in this case.
5933    
5934    Returns 1 if found, 0 otherwise. */
5935
5936 static int
5937 find_struct_field (char *name, struct type *type, int offset,
5938                    struct type **field_type_p,
5939                    int *byte_offset_p, int *bit_offset_p, int *bit_size_p,
5940                    int *index_p)
5941 {
5942   int i;
5943
5944   type = ada_check_typedef (type);
5945
5946   if (field_type_p != NULL)
5947     *field_type_p = NULL;
5948   if (byte_offset_p != NULL)
5949     *byte_offset_p = 0;
5950   if (bit_offset_p != NULL)
5951     *bit_offset_p = 0;
5952   if (bit_size_p != NULL)
5953     *bit_size_p = 0;
5954
5955   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
5956     {
5957       int bit_pos = TYPE_FIELD_BITPOS (type, i);
5958       int fld_offset = offset + bit_pos / 8;
5959       char *t_field_name = TYPE_FIELD_NAME (type, i);
5960
5961       if (t_field_name == NULL)
5962         continue;
5963
5964       else if (name != NULL && field_name_match (t_field_name, name))
5965         {
5966           int bit_size = TYPE_FIELD_BITSIZE (type, i);
5967           if (field_type_p != NULL)
5968             *field_type_p = TYPE_FIELD_TYPE (type, i);
5969           if (byte_offset_p != NULL)
5970             *byte_offset_p = fld_offset;
5971           if (bit_offset_p != NULL)
5972             *bit_offset_p = bit_pos % 8;
5973           if (bit_size_p != NULL)
5974             *bit_size_p = bit_size;
5975           return 1;
5976         }
5977       else if (ada_is_wrapper_field (type, i))
5978         {
5979           if (find_struct_field (name, TYPE_FIELD_TYPE (type, i), fld_offset,
5980                                  field_type_p, byte_offset_p, bit_offset_p,
5981                                  bit_size_p, index_p))
5982             return 1;
5983         }
5984       else if (ada_is_variant_part (type, i))
5985         {
5986           /* PNH: Wait.  Do we ever execute this section, or is ARG always of 
5987              fixed type?? */
5988           int j;
5989           struct type *field_type
5990             = ada_check_typedef (TYPE_FIELD_TYPE (type, i));
5991
5992           for (j = 0; j < TYPE_NFIELDS (field_type); j += 1)
5993             {
5994               if (find_struct_field (name, TYPE_FIELD_TYPE (field_type, j),
5995                                      fld_offset
5996                                      + TYPE_FIELD_BITPOS (field_type, j) / 8,
5997                                      field_type_p, byte_offset_p,
5998                                      bit_offset_p, bit_size_p, index_p))
5999                 return 1;
6000             }
6001         }
6002       else if (index_p != NULL)
6003         *index_p += 1;
6004     }
6005   return 0;
6006 }
6007
6008 /* Number of user-visible fields in record type TYPE. */
6009
6010 static int
6011 num_visible_fields (struct type *type)
6012 {
6013   int n;
6014   n = 0;
6015   find_struct_field (NULL, type, 0, NULL, NULL, NULL, NULL, &n);
6016   return n;
6017 }
6018
6019 /* Look for a field NAME in ARG.  Adjust the address of ARG by OFFSET bytes,
6020    and search in it assuming it has (class) type TYPE.
6021    If found, return value, else return NULL.
6022
6023    Searches recursively through wrapper fields (e.g., '_parent').  */
6024
6025 static struct value *
6026 ada_search_struct_field (char *name, struct value *arg, int offset,
6027                          struct type *type)
6028 {
6029   int i;
6030   type = ada_check_typedef (type);
6031
6032   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
6033     {
6034       char *t_field_name = TYPE_FIELD_NAME (type, i);
6035
6036       if (t_field_name == NULL)
6037         continue;
6038
6039       else if (field_name_match (t_field_name, name))
6040         return ada_value_primitive_field (arg, offset, i, type);
6041
6042       else if (ada_is_wrapper_field (type, i))
6043         {
6044           struct value *v =     /* Do not let indent join lines here. */
6045             ada_search_struct_field (name, arg,
6046                                      offset + TYPE_FIELD_BITPOS (type, i) / 8,
6047                                      TYPE_FIELD_TYPE (type, i));
6048           if (v != NULL)
6049             return v;
6050         }
6051
6052       else if (ada_is_variant_part (type, i))
6053         {
6054           /* PNH: Do we ever get here?  See find_struct_field. */
6055           int j;
6056           struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type, i));
6057           int var_offset = offset + TYPE_FIELD_BITPOS (type, i) / 8;
6058
6059           for (j = 0; j < TYPE_NFIELDS (field_type); j += 1)
6060             {
6061               struct value *v = ada_search_struct_field /* Force line break.  */
6062                 (name, arg,
6063                  var_offset + TYPE_FIELD_BITPOS (field_type, j) / 8,
6064                  TYPE_FIELD_TYPE (field_type, j));
6065               if (v != NULL)
6066                 return v;
6067             }
6068         }
6069     }
6070   return NULL;
6071 }
6072
6073 static struct value *ada_index_struct_field_1 (int *, struct value *,
6074                                                int, struct type *);
6075
6076
6077 /* Return field #INDEX in ARG, where the index is that returned by
6078  * find_struct_field through its INDEX_P argument.  Adjust the address
6079  * of ARG by OFFSET bytes, and search in it assuming it has (class) type TYPE.
6080  * If found, return value, else return NULL. */
6081
6082 static struct value *
6083 ada_index_struct_field (int index, struct value *arg, int offset,
6084                         struct type *type)
6085 {
6086   return ada_index_struct_field_1 (&index, arg, offset, type);
6087 }
6088
6089
6090 /* Auxiliary function for ada_index_struct_field.  Like
6091  * ada_index_struct_field, but takes index from *INDEX_P and modifies
6092  * *INDEX_P. */
6093
6094 static struct value *
6095 ada_index_struct_field_1 (int *index_p, struct value *arg, int offset,
6096                           struct type *type)
6097 {
6098   int i;
6099   type = ada_check_typedef (type);
6100
6101   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
6102     {
6103       if (TYPE_FIELD_NAME (type, i) == NULL)
6104         continue;
6105       else if (ada_is_wrapper_field (type, i))
6106         {
6107           struct value *v =     /* Do not let indent join lines here. */
6108             ada_index_struct_field_1 (index_p, arg,
6109                                       offset + TYPE_FIELD_BITPOS (type, i) / 8,
6110                                       TYPE_FIELD_TYPE (type, i));
6111           if (v != NULL)
6112             return v;
6113         }
6114
6115       else if (ada_is_variant_part (type, i))
6116         {
6117           /* PNH: Do we ever get here?  See ada_search_struct_field,
6118              find_struct_field. */
6119           error (_("Cannot assign this kind of variant record"));
6120         }
6121       else if (*index_p == 0)
6122         return ada_value_primitive_field (arg, offset, i, type);
6123       else
6124         *index_p -= 1;
6125     }
6126   return NULL;
6127 }
6128
6129 /* Given ARG, a value of type (pointer or reference to a)*
6130    structure/union, extract the component named NAME from the ultimate
6131    target structure/union and return it as a value with its
6132    appropriate type.
6133
6134    The routine searches for NAME among all members of the structure itself
6135    and (recursively) among all members of any wrapper members
6136    (e.g., '_parent').
6137
6138    If NO_ERR, then simply return NULL in case of error, rather than 
6139    calling error.  */
6140
6141 struct value *
6142 ada_value_struct_elt (struct value *arg, char *name, int no_err)
6143 {
6144   struct type *t, *t1;
6145   struct value *v;
6146
6147   v = NULL;
6148   t1 = t = ada_check_typedef (value_type (arg));
6149   if (TYPE_CODE (t) == TYPE_CODE_REF)
6150     {
6151       t1 = TYPE_TARGET_TYPE (t);
6152       if (t1 == NULL)
6153         goto BadValue;
6154       t1 = ada_check_typedef (t1);
6155       if (TYPE_CODE (t1) == TYPE_CODE_PTR)
6156         {
6157           arg = coerce_ref (arg);
6158           t = t1;
6159         }
6160     }
6161
6162   while (TYPE_CODE (t) == TYPE_CODE_PTR)
6163     {
6164       t1 = TYPE_TARGET_TYPE (t);
6165       if (t1 == NULL)
6166         goto BadValue;
6167       t1 = ada_check_typedef (t1);
6168       if (TYPE_CODE (t1) == TYPE_CODE_PTR)
6169         {
6170           arg = value_ind (arg);
6171           t = t1;
6172         }
6173       else
6174         break;
6175     }
6176
6177   if (TYPE_CODE (t1) != TYPE_CODE_STRUCT && TYPE_CODE (t1) != TYPE_CODE_UNION)
6178     goto BadValue;
6179
6180   if (t1 == t)
6181     v = ada_search_struct_field (name, arg, 0, t);
6182   else
6183     {
6184       int bit_offset, bit_size, byte_offset;
6185       struct type *field_type;
6186       CORE_ADDR address;
6187
6188       if (TYPE_CODE (t) == TYPE_CODE_PTR)
6189         address = value_as_address (arg);
6190       else
6191         address = unpack_pointer (t, value_contents (arg));
6192
6193       t1 = ada_to_fixed_type (ada_get_base_type (t1), NULL, address, NULL, 1);
6194       if (find_struct_field (name, t1, 0,
6195                              &field_type, &byte_offset, &bit_offset,
6196                              &bit_size, NULL))
6197         {
6198           if (bit_size != 0)
6199             {
6200               if (TYPE_CODE (t) == TYPE_CODE_REF)
6201                 arg = ada_coerce_ref (arg);
6202               else
6203                 arg = ada_value_ind (arg);
6204               v = ada_value_primitive_packed_val (arg, NULL, byte_offset,
6205                                                   bit_offset, bit_size,
6206                                                   field_type);
6207             }
6208           else
6209             v = value_at_lazy (field_type, address + byte_offset);
6210         }
6211     }
6212
6213   if (v != NULL || no_err)
6214     return v;
6215   else
6216     error (_("There is no member named %s."), name);
6217
6218  BadValue:
6219   if (no_err)
6220     return NULL;
6221   else
6222     error (_("Attempt to extract a component of a value that is not a record."));
6223 }
6224
6225 /* Given a type TYPE, look up the type of the component of type named NAME.
6226    If DISPP is non-null, add its byte displacement from the beginning of a
6227    structure (pointed to by a value) of type TYPE to *DISPP (does not
6228    work for packed fields).
6229
6230    Matches any field whose name has NAME as a prefix, possibly
6231    followed by "___".
6232
6233    TYPE can be either a struct or union. If REFOK, TYPE may also 
6234    be a (pointer or reference)+ to a struct or union, and the
6235    ultimate target type will be searched.
6236
6237    Looks recursively into variant clauses and parent types.
6238
6239    If NOERR is nonzero, return NULL if NAME is not suitably defined or
6240    TYPE is not a type of the right kind.  */
6241
6242 static struct type *
6243 ada_lookup_struct_elt_type (struct type *type, char *name, int refok,
6244                             int noerr, int *dispp)
6245 {
6246   int i;
6247
6248   if (name == NULL)
6249     goto BadName;
6250
6251   if (refok && type != NULL)
6252     while (1)
6253       {
6254         type = ada_check_typedef (type);
6255         if (TYPE_CODE (type) != TYPE_CODE_PTR
6256             && TYPE_CODE (type) != TYPE_CODE_REF)
6257           break;
6258         type = TYPE_TARGET_TYPE (type);
6259       }
6260
6261   if (type == NULL
6262       || (TYPE_CODE (type) != TYPE_CODE_STRUCT
6263           && TYPE_CODE (type) != TYPE_CODE_UNION))
6264     {
6265       if (noerr)
6266         return NULL;
6267       else
6268         {
6269           target_terminal_ours ();
6270           gdb_flush (gdb_stdout);
6271           if (type == NULL)
6272             error (_("Type (null) is not a structure or union type"));
6273           else
6274             {
6275               /* XXX: type_sprint */
6276               fprintf_unfiltered (gdb_stderr, _("Type "));
6277               type_print (type, "", gdb_stderr, -1);
6278               error (_(" is not a structure or union type"));
6279             }
6280         }
6281     }
6282
6283   type = to_static_fixed_type (type);
6284
6285   for (i = 0; i < TYPE_NFIELDS (type); i += 1)
6286     {
6287       char *t_field_name = TYPE_FIELD_NAME (type, i);
6288       struct type *t;
6289       int disp;
6290
6291       if (t_field_name == NULL)
6292         continue;
6293
6294       else if (field_name_match (t_field_name, name))
6295         {
6296           if (dispp != NULL)
6297             *dispp += TYPE_FIELD_BITPOS (type, i) / 8;
6298           return ada_check_typedef (TYPE_FIELD_TYPE (type, i));
6299         }
6300
6301       else if (ada_is_wrapper_field (type, i))
6302         {
6303           disp = 0;
6304           t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (type, i), name,
6305                                           0, 1, &disp);
6306           if (t != NULL)
6307             {
6308               if (dispp != NULL)
6309                 *dispp += disp + TYPE_FIELD_BITPOS (type, i) / 8;
6310               return t;
6311             }
6312         }
6313
6314       else if (ada_is_variant_part (type, i))
6315         {
6316           int j;
6317           struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type, i));
6318
6319           for (j = TYPE_NFIELDS (field_type) - 1; j >= 0; j -= 1)
6320             {
6321               /* FIXME pnh 2008/01/26: We check for a field that is
6322                  NOT wrapped in a struct, since the compiler sometimes
6323                  generates these for unchecked variant types.  Revisit
6324                  if the compiler changes this practice. */
6325               char *v_field_name = TYPE_FIELD_NAME (field_type, j);
6326               disp = 0;
6327               if (v_field_name != NULL 
6328                   && field_name_match (v_field_name, name))
6329                 t = ada_check_typedef (TYPE_FIELD_TYPE (field_type, j));
6330               else
6331                 t = ada_lookup_struct_elt_type (TYPE_FIELD_TYPE (field_type, j),
6332                                                 name, 0, 1, &disp);
6333
6334               if (t != NULL)
6335                 {
6336                   if (dispp != NULL)
6337                     *dispp += disp + TYPE_FIELD_BITPOS (type, i) / 8;
6338                   return t;
6339                 }
6340             }
6341         }
6342
6343     }
6344
6345 BadName:
6346   if (!noerr)
6347     {
6348       target_terminal_ours ();
6349       gdb_flush (gdb_stdout);
6350       if (name == NULL)
6351         {
6352           /* XXX: type_sprint */
6353           fprintf_unfiltered (gdb_stderr, _("Type "));
6354           type_print (type, "", gdb_stderr, -1);
6355           error (_(" has no component named <null>"));
6356         }
6357       else
6358         {
6359           /* XXX: type_sprint */
6360           fprintf_unfiltered (gdb_stderr, _("Type "));
6361           type_print (type, "", gdb_stderr, -1);
6362           error (_(" has no component named %s"), name);
6363         }
6364     }
6365
6366   return NULL;
6367 }
6368
6369 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
6370    within a value of type OUTER_TYPE, return true iff VAR_TYPE
6371    represents an unchecked union (that is, the variant part of a
6372    record that is named in an Unchecked_Union pragma). */
6373
6374 static int
6375 is_unchecked_variant (struct type *var_type, struct type *outer_type)
6376 {
6377   char *discrim_name = ada_variant_discrim_name (var_type);
6378   return (ada_lookup_struct_elt_type (outer_type, discrim_name, 0, 1, NULL) 
6379           == NULL);
6380 }
6381
6382
6383 /* Assuming that VAR_TYPE is the type of a variant part of a record (a union),
6384    within a value of type OUTER_TYPE that is stored in GDB at
6385    OUTER_VALADDR, determine which variant clause (field number in VAR_TYPE,
6386    numbering from 0) is applicable.  Returns -1 if none are.  */
6387
6388 int
6389 ada_which_variant_applies (struct type *var_type, struct type *outer_type,
6390                            const gdb_byte *outer_valaddr)
6391 {
6392   int others_clause;
6393   int i;
6394   char *discrim_name = ada_variant_discrim_name (var_type);
6395   struct value *outer;
6396   struct value *discrim;
6397   LONGEST discrim_val;
6398
6399   outer = value_from_contents_and_address (outer_type, outer_valaddr, 0);
6400   discrim = ada_value_struct_elt (outer, discrim_name, 1);
6401   if (discrim == NULL)
6402     return -1;
6403   discrim_val = value_as_long (discrim);
6404
6405   others_clause = -1;
6406   for (i = 0; i < TYPE_NFIELDS (var_type); i += 1)
6407     {
6408       if (ada_is_others_clause (var_type, i))
6409         others_clause = i;
6410       else if (ada_in_variant (discrim_val, var_type, i))
6411         return i;
6412     }
6413
6414   return others_clause;
6415 }
6416 \f
6417
6418
6419                                 /* Dynamic-Sized Records */
6420
6421 /* Strategy: The type ostensibly attached to a value with dynamic size
6422    (i.e., a size that is not statically recorded in the debugging
6423    data) does not accurately reflect the size or layout of the value.
6424    Our strategy is to convert these values to values with accurate,
6425    conventional types that are constructed on the fly.  */
6426
6427 /* There is a subtle and tricky problem here.  In general, we cannot
6428    determine the size of dynamic records without its data.  However,
6429    the 'struct value' data structure, which GDB uses to represent
6430    quantities in the inferior process (the target), requires the size
6431    of the type at the time of its allocation in order to reserve space
6432    for GDB's internal copy of the data.  That's why the
6433    'to_fixed_xxx_type' routines take (target) addresses as parameters,
6434    rather than struct value*s.
6435
6436    However, GDB's internal history variables ($1, $2, etc.) are
6437    struct value*s containing internal copies of the data that are not, in
6438    general, the same as the data at their corresponding addresses in
6439    the target.  Fortunately, the types we give to these values are all
6440    conventional, fixed-size types (as per the strategy described
6441    above), so that we don't usually have to perform the
6442    'to_fixed_xxx_type' conversions to look at their values.
6443    Unfortunately, there is one exception: if one of the internal
6444    history variables is an array whose elements are unconstrained
6445    records, then we will need to create distinct fixed types for each
6446    element selected.  */
6447
6448 /* The upshot of all of this is that many routines take a (type, host
6449    address, target address) triple as arguments to represent a value.
6450    The host address, if non-null, is supposed to contain an internal
6451    copy of the relevant data; otherwise, the program is to consult the
6452    target at the target address.  */
6453
6454 /* Assuming that VAL0 represents a pointer value, the result of
6455    dereferencing it.  Differs from value_ind in its treatment of
6456    dynamic-sized types.  */
6457
6458 struct value *
6459 ada_value_ind (struct value *val0)
6460 {
6461   struct value *val = unwrap_value (value_ind (val0));
6462   return ada_to_fixed_value (val);
6463 }
6464
6465 /* The value resulting from dereferencing any "reference to"
6466    qualifiers on VAL0.  */
6467
6468 static struct value *
6469 ada_coerce_ref (struct value *val0)
6470 {
6471   if (TYPE_CODE (value_type (val0)) == TYPE_CODE_REF)
6472     {
6473       struct value *val = val0;
6474       val = coerce_ref (val);
6475       val = unwrap_value (val);
6476       return ada_to_fixed_value (val);
6477     }
6478   else
6479     return val0;
6480 }
6481
6482 /* Return OFF rounded upward if necessary to a multiple of
6483    ALIGNMENT (a power of 2).  */
6484
6485 static unsigned int
6486 align_value (unsigned int off, unsigned int alignment)
6487 {
6488   return (off + alignment - 1) & ~(alignment - 1);
6489 }
6490
6491 /* Return the bit alignment required for field #F of template type TYPE.  */
6492
6493 static unsigned int
6494 field_alignment (struct type *type, int f)
6495 {
6496   const char *name = TYPE_FIELD_NAME (type, f);
6497   int len;
6498   int align_offset;
6499
6500   /* The field name should never be null, unless the debugging information
6501      is somehow malformed.  In this case, we assume the field does not
6502      require any alignment.  */
6503   if (name == NULL)
6504     return 1;
6505
6506   len = strlen (name);
6507
6508   if (!isdigit (name[len - 1]))
6509     return 1;
6510
6511   if (isdigit (name[len - 2]))
6512     align_offset = len - 2;
6513   else
6514     align_offset = len - 1;
6515
6516   if (align_offset < 7 || strncmp ("___XV", name + align_offset - 6, 5) != 0)
6517     return TARGET_CHAR_BIT;
6518
6519   return atoi (name + align_offset) * TARGET_CHAR_BIT;
6520 }
6521
6522 /* Find a symbol named NAME.  Ignores ambiguity.  */
6523
6524 struct symbol *
6525 ada_find_any_symbol (const char *name)
6526 {
6527   struct symbol *sym;
6528
6529   sym = standard_lookup (name, get_selected_block (NULL), VAR_DOMAIN);
6530   if (sym != NULL && SYMBOL_CLASS (sym) == LOC_TYPEDEF)
6531     return sym;
6532
6533   sym = standard_lookup (name, NULL, STRUCT_DOMAIN);
6534   return sym;
6535 }
6536
6537 /* Find a type named NAME.  Ignores ambiguity.  */
6538
6539 struct type *
6540 ada_find_any_type (const char *name)
6541 {
6542   struct symbol *sym = ada_find_any_symbol (name);
6543   struct type *type = NULL;
6544
6545   if (sym != NULL)
6546     type = SYMBOL_TYPE (sym);
6547
6548   if (type == NULL)
6549     type = language_lookup_primitive_type_by_name
6550       (language_def (language_ada), current_gdbarch, name);
6551
6552   return type;
6553 }
6554
6555 /* Given NAME and an associated BLOCK, search all symbols for
6556    NAME suffixed with  "___XR", which is the ``renaming'' symbol
6557    associated to NAME.  Return this symbol if found, return
6558    NULL otherwise.  */
6559
6560 struct symbol *
6561 ada_find_renaming_symbol (const char *name, struct block *block)
6562 {
6563   struct symbol *sym;
6564
6565   sym = find_old_style_renaming_symbol (name, block);
6566
6567   if (sym != NULL)
6568     return sym;
6569
6570   /* Not right yet.  FIXME pnh 7/20/2007. */
6571   sym = ada_find_any_symbol (name);
6572   if (sym != NULL && strstr (SYMBOL_LINKAGE_NAME (sym), "___XR") != NULL)
6573     return sym;
6574   else
6575     return NULL;
6576 }
6577
6578 static struct symbol *
6579 find_old_style_renaming_symbol (const char *name, struct block *block)
6580 {
6581   const struct symbol *function_sym = block_linkage_function (block);
6582   char *rename;
6583
6584   if (function_sym != NULL)
6585     {
6586       /* If the symbol is defined inside a function, NAME is not fully
6587          qualified.  This means we need to prepend the function name
6588          as well as adding the ``___XR'' suffix to build the name of
6589          the associated renaming symbol.  */
6590       char *function_name = SYMBOL_LINKAGE_NAME (function_sym);
6591       /* Function names sometimes contain suffixes used
6592          for instance to qualify nested subprograms.  When building
6593          the XR type name, we need to make sure that this suffix is
6594          not included.  So do not include any suffix in the function
6595          name length below.  */
6596       const int function_name_len = ada_name_prefix_len (function_name);
6597       const int rename_len = function_name_len + 2      /*  "__" */
6598         + strlen (name) + 6 /* "___XR\0" */ ;
6599
6600       /* Strip the suffix if necessary.  */
6601       function_name[function_name_len] = '\0';
6602
6603       /* Library-level functions are a special case, as GNAT adds
6604          a ``_ada_'' prefix to the function name to avoid namespace
6605          pollution.  However, the renaming symbols themselves do not
6606          have this prefix, so we need to skip this prefix if present.  */
6607       if (function_name_len > 5 /* "_ada_" */
6608           && strstr (function_name, "_ada_") == function_name)
6609         function_name = function_name + 5;
6610
6611       rename = (char *) alloca (rename_len * sizeof (char));
6612       sprintf (rename, "%s__%s___XR", function_name, name);
6613     }
6614   else
6615     {
6616       const int rename_len = strlen (name) + 6;
6617       rename = (char *) alloca (rename_len * sizeof (char));
6618       sprintf (rename, "%s___XR", name);
6619     }
6620
6621   return ada_find_any_symbol (rename);
6622 }
6623
6624 /* Because of GNAT encoding conventions, several GDB symbols may match a
6625    given type name.  If the type denoted by TYPE0 is to be preferred to
6626    that of TYPE1 for purposes of type printing, return non-zero;
6627    otherwise return 0.  */
6628
6629 int
6630 ada_prefer_type (struct type *type0, struct type *type1)
6631 {
6632   if (type1 == NULL)
6633     return 1;
6634   else if (type0 == NULL)
6635     return 0;
6636   else if (TYPE_CODE (type1) == TYPE_CODE_VOID)
6637     return 1;
6638   else if (TYPE_CODE (type0) == TYPE_CODE_VOID)
6639     return 0;
6640   else if (TYPE_NAME (type1) == NULL && TYPE_NAME (type0) != NULL)
6641     return 1;
6642   else if (ada_is_packed_array_type (type0))
6643     return 1;
6644   else if (ada_is_array_descriptor_type (type0)
6645            && !ada_is_array_descriptor_type (type1))
6646     return 1;
6647   else
6648     {
6649       const char *type0_name = type_name_no_tag (type0);
6650       const char *type1_name = type_name_no_tag (type1);
6651
6652       if (type0_name != NULL && strstr (type0_name, "___XR") != NULL
6653           && (type1_name == NULL || strstr (type1_name, "___XR") == NULL))
6654         return 1;
6655     }
6656   return 0;
6657 }
6658
6659 /* The name of TYPE, which is either its TYPE_NAME, or, if that is
6660    null, its TYPE_TAG_NAME.  Null if TYPE is null.  */
6661
6662 char *
6663 ada_type_name (struct type *type)
6664 {
6665   if (type == NULL)
6666     return NULL;
6667   else if (TYPE_NAME (type) != NULL)
6668     return TYPE_NAME (type);
6669   else
6670     return TYPE_TAG_NAME (type);
6671 }
6672
6673 /* Find a parallel type to TYPE whose name is formed by appending
6674    SUFFIX to the name of TYPE.  */
6675
6676 struct type *
6677 ada_find_parallel_type (struct type *type, const char *suffix)
6678 {
6679   static char *name;
6680   static size_t name_len = 0;
6681   int len;
6682   char *typename = ada_type_name (type);
6683
6684   if (typename == NULL)
6685     return NULL;
6686
6687   len = strlen (typename);
6688
6689   GROW_VECT (name, name_len, len + strlen (suffix) + 1);
6690
6691   strcpy (name, typename);
6692   strcpy (name + len, suffix);
6693
6694   return ada_find_any_type (name);
6695 }
6696
6697
6698 /* If TYPE is a variable-size record type, return the corresponding template
6699    type describing its fields.  Otherwise, return NULL.  */
6700
6701 static struct type *
6702 dynamic_template_type (struct type *type)
6703 {
6704   type = ada_check_typedef (type);
6705
6706   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT
6707       || ada_type_name (type) == NULL)
6708     return NULL;
6709   else
6710     {
6711       int len = strlen (ada_type_name (type));
6712       if (len > 6 && strcmp (ada_type_name (type) + len - 6, "___XVE") == 0)
6713         return type;
6714       else
6715         return ada_find_parallel_type (type, "___XVE");
6716     }
6717 }
6718
6719 /* Assuming that TEMPL_TYPE is a union or struct type, returns
6720    non-zero iff field FIELD_NUM of TEMPL_TYPE has dynamic size.  */
6721
6722 static int
6723 is_dynamic_field (struct type *templ_type, int field_num)
6724 {
6725   const char *name = TYPE_FIELD_NAME (templ_type, field_num);
6726   return name != NULL
6727     && TYPE_CODE (TYPE_FIELD_TYPE (templ_type, field_num)) == TYPE_CODE_PTR
6728     && strstr (name, "___XVL") != NULL;
6729 }
6730
6731 /* The index of the variant field of TYPE, or -1 if TYPE does not
6732    represent a variant record type.  */
6733
6734 static int
6735 variant_field_index (struct type *type)
6736 {
6737   int f;
6738
6739   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_STRUCT)
6740     return -1;
6741
6742   for (f = 0; f < TYPE_NFIELDS (type); f += 1)
6743     {
6744       if (ada_is_variant_part (type, f))
6745         return f;
6746     }
6747   return -1;
6748 }
6749
6750 /* A record type with no fields.  */
6751
6752 static struct type *
6753 empty_record (struct objfile *objfile)
6754 {
6755   struct type *type = alloc_type (objfile);
6756   TYPE_CODE (type) = TYPE_CODE_STRUCT;
6757   TYPE_NFIELDS (type) = 0;
6758   TYPE_FIELDS (type) = NULL;
6759   INIT_CPLUS_SPECIFIC (type);
6760   TYPE_NAME (type) = "<empty>";
6761   TYPE_TAG_NAME (type) = NULL;
6762   TYPE_LENGTH (type) = 0;
6763   return type;
6764 }
6765
6766 /* An ordinary record type (with fixed-length fields) that describes
6767    the value of type TYPE at VALADDR or ADDRESS (see comments at
6768    the beginning of this section) VAL according to GNAT conventions.
6769    DVAL0 should describe the (portion of a) record that contains any
6770    necessary discriminants.  It should be NULL if value_type (VAL) is
6771    an outer-level type (i.e., as opposed to a branch of a variant.)  A
6772    variant field (unless unchecked) is replaced by a particular branch
6773    of the variant.
6774
6775    If not KEEP_DYNAMIC_FIELDS, then all fields whose position or
6776    length are not statically known are discarded.  As a consequence,
6777    VALADDR, ADDRESS and DVAL0 are ignored.
6778
6779    NOTE: Limitations: For now, we assume that dynamic fields and
6780    variants occupy whole numbers of bytes.  However, they need not be
6781    byte-aligned.  */
6782
6783 struct type *
6784 ada_template_to_fixed_record_type_1 (struct type *type,
6785                                      const gdb_byte *valaddr,
6786                                      CORE_ADDR address, struct value *dval0,
6787                                      int keep_dynamic_fields)
6788 {
6789   struct value *mark = value_mark ();
6790   struct value *dval;
6791   struct type *rtype;
6792   int nfields, bit_len;
6793   int variant_field;
6794   long off;
6795   int fld_bit_len, bit_incr;
6796   int f;
6797
6798   /* Compute the number of fields in this record type that are going
6799      to be processed: unless keep_dynamic_fields, this includes only
6800      fields whose position and length are static will be processed.  */
6801   if (keep_dynamic_fields)
6802     nfields = TYPE_NFIELDS (type);
6803   else
6804     {
6805       nfields = 0;
6806       while (nfields < TYPE_NFIELDS (type)
6807              && !ada_is_variant_part (type, nfields)
6808              && !is_dynamic_field (type, nfields))
6809         nfields++;
6810     }
6811
6812   rtype = alloc_type (TYPE_OBJFILE (type));
6813   TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
6814   INIT_CPLUS_SPECIFIC (rtype);
6815   TYPE_NFIELDS (rtype) = nfields;
6816   TYPE_FIELDS (rtype) = (struct field *)
6817     TYPE_ALLOC (rtype, nfields * sizeof (struct field));
6818   memset (TYPE_FIELDS (rtype), 0, sizeof (struct field) * nfields);
6819   TYPE_NAME (rtype) = ada_type_name (type);
6820   TYPE_TAG_NAME (rtype) = NULL;
6821   TYPE_FIXED_INSTANCE (rtype) = 1;
6822
6823   off = 0;
6824   bit_len = 0;
6825   variant_field = -1;
6826
6827   for (f = 0; f < nfields; f += 1)
6828     {
6829       off = align_value (off, field_alignment (type, f))
6830         + TYPE_FIELD_BITPOS (type, f);
6831       TYPE_FIELD_BITPOS (rtype, f) = off;
6832       TYPE_FIELD_BITSIZE (rtype, f) = 0;
6833
6834       if (ada_is_variant_part (type, f))
6835         {
6836           variant_field = f;
6837           fld_bit_len = bit_incr = 0;
6838         }
6839       else if (is_dynamic_field (type, f))
6840         {
6841           if (dval0 == NULL)
6842             {
6843               /* rtype's length is computed based on the run-time
6844                  value of discriminants.  If the discriminants are not
6845                  initialized, the type size may be completely bogus and
6846                  GDB may fail to allocate a value for it. So check the
6847                  size first before creating the value.  */
6848               check_size (rtype);
6849               dval = value_from_contents_and_address (rtype, valaddr, address);
6850             }
6851           else
6852             dval = dval0;
6853
6854           /* Get the fixed type of the field. Note that, in this case, we
6855              do not want to get the real type out of the tag: if the current
6856              field is the parent part of a tagged record, we will get the
6857              tag of the object. Clearly wrong: the real type of the parent
6858              is not the real type of the child. We would end up in an infinite
6859              loop.  */
6860           TYPE_FIELD_TYPE (rtype, f) =
6861             ada_to_fixed_type
6862             (ada_get_base_type
6863              (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type, f))),
6864              cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
6865              cond_offset_target (address, off / TARGET_CHAR_BIT), dval, 0);
6866           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
6867           bit_incr = fld_bit_len =
6868             TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, f)) * TARGET_CHAR_BIT;
6869         }
6870       else
6871         {
6872           TYPE_FIELD_TYPE (rtype, f) = TYPE_FIELD_TYPE (type, f);
6873           TYPE_FIELD_NAME (rtype, f) = TYPE_FIELD_NAME (type, f);
6874           if (TYPE_FIELD_BITSIZE (type, f) > 0)
6875             bit_incr = fld_bit_len =
6876               TYPE_FIELD_BITSIZE (rtype, f) = TYPE_FIELD_BITSIZE (type, f);
6877           else
6878             bit_incr = fld_bit_len =
6879               TYPE_LENGTH (TYPE_FIELD_TYPE (type, f)) * TARGET_CHAR_BIT;
6880         }
6881       if (off + fld_bit_len > bit_len)
6882         bit_len = off + fld_bit_len;
6883       off += bit_incr;
6884       TYPE_LENGTH (rtype) =
6885         align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
6886     }
6887
6888   /* We handle the variant part, if any, at the end because of certain
6889      odd cases in which it is re-ordered so as NOT to be the last field of
6890      the record.  This can happen in the presence of representation
6891      clauses.  */
6892   if (variant_field >= 0)
6893     {
6894       struct type *branch_type;
6895
6896       off = TYPE_FIELD_BITPOS (rtype, variant_field);
6897
6898       if (dval0 == NULL)
6899         dval = value_from_contents_and_address (rtype, valaddr, address);
6900       else
6901         dval = dval0;
6902
6903       branch_type =
6904         to_fixed_variant_branch_type
6905         (TYPE_FIELD_TYPE (type, variant_field),
6906          cond_offset_host (valaddr, off / TARGET_CHAR_BIT),
6907          cond_offset_target (address, off / TARGET_CHAR_BIT), dval);
6908       if (branch_type == NULL)
6909         {
6910           for (f = variant_field + 1; f < TYPE_NFIELDS (rtype); f += 1)
6911             TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
6912           TYPE_NFIELDS (rtype) -= 1;
6913         }
6914       else
6915         {
6916           TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
6917           TYPE_FIELD_NAME (rtype, variant_field) = "S";
6918           fld_bit_len =
6919             TYPE_LENGTH (TYPE_FIELD_TYPE (rtype, variant_field)) *
6920             TARGET_CHAR_BIT;
6921           if (off + fld_bit_len > bit_len)
6922             bit_len = off + fld_bit_len;
6923           TYPE_LENGTH (rtype) =
6924             align_value (bit_len, TARGET_CHAR_BIT) / TARGET_CHAR_BIT;
6925         }
6926     }
6927
6928   /* According to exp_dbug.ads, the size of TYPE for variable-size records
6929      should contain the alignment of that record, which should be a strictly
6930      positive value.  If null or negative, then something is wrong, most
6931      probably in the debug info.  In that case, we don't round up the size
6932      of the resulting type. If this record is not part of another structure,
6933      the current RTYPE length might be good enough for our purposes.  */
6934   if (TYPE_LENGTH (type) <= 0)
6935     {
6936       if (TYPE_NAME (rtype))
6937         warning (_("Invalid type size for `%s' detected: %d."),
6938                  TYPE_NAME (rtype), TYPE_LENGTH (type));
6939       else
6940         warning (_("Invalid type size for <unnamed> detected: %d."),
6941                  TYPE_LENGTH (type));
6942     }
6943   else
6944     {
6945       TYPE_LENGTH (rtype) = align_value (TYPE_LENGTH (rtype),
6946                                          TYPE_LENGTH (type));
6947     }
6948
6949   value_free_to_mark (mark);
6950   if (TYPE_LENGTH (rtype) > varsize_limit)
6951     error (_("record type with dynamic size is larger than varsize-limit"));
6952   return rtype;
6953 }
6954
6955 /* As for ada_template_to_fixed_record_type_1 with KEEP_DYNAMIC_FIELDS
6956    of 1.  */
6957
6958 static struct type *
6959 template_to_fixed_record_type (struct type *type, const gdb_byte *valaddr,
6960                                CORE_ADDR address, struct value *dval0)
6961 {
6962   return ada_template_to_fixed_record_type_1 (type, valaddr,
6963                                               address, dval0, 1);
6964 }
6965
6966 /* An ordinary record type in which ___XVL-convention fields and
6967    ___XVU- and ___XVN-convention field types in TYPE0 are replaced with
6968    static approximations, containing all possible fields.  Uses
6969    no runtime values.  Useless for use in values, but that's OK,
6970    since the results are used only for type determinations.   Works on both
6971    structs and unions.  Representation note: to save space, we memorize
6972    the result of this function in the TYPE_TARGET_TYPE of the
6973    template type.  */
6974
6975 static struct type *
6976 template_to_static_fixed_type (struct type *type0)
6977 {
6978   struct type *type;
6979   int nfields;
6980   int f;
6981
6982   if (TYPE_TARGET_TYPE (type0) != NULL)
6983     return TYPE_TARGET_TYPE (type0);
6984
6985   nfields = TYPE_NFIELDS (type0);
6986   type = type0;
6987
6988   for (f = 0; f < nfields; f += 1)
6989     {
6990       struct type *field_type = ada_check_typedef (TYPE_FIELD_TYPE (type0, f));
6991       struct type *new_type;
6992
6993       if (is_dynamic_field (type0, f))
6994         new_type = to_static_fixed_type (TYPE_TARGET_TYPE (field_type));
6995       else
6996         new_type = static_unwrap_type (field_type);
6997       if (type == type0 && new_type != field_type)
6998         {
6999           TYPE_TARGET_TYPE (type0) = type = alloc_type (TYPE_OBJFILE (type0));
7000           TYPE_CODE (type) = TYPE_CODE (type0);
7001           INIT_CPLUS_SPECIFIC (type);
7002           TYPE_NFIELDS (type) = nfields;
7003           TYPE_FIELDS (type) = (struct field *)
7004             TYPE_ALLOC (type, nfields * sizeof (struct field));
7005           memcpy (TYPE_FIELDS (type), TYPE_FIELDS (type0),
7006                   sizeof (struct field) * nfields);
7007           TYPE_NAME (type) = ada_type_name (type0);
7008           TYPE_TAG_NAME (type) = NULL;
7009           TYPE_FIXED_INSTANCE (type) = 1;
7010           TYPE_LENGTH (type) = 0;
7011         }
7012       TYPE_FIELD_TYPE (type, f) = new_type;
7013       TYPE_FIELD_NAME (type, f) = TYPE_FIELD_NAME (type0, f);
7014     }
7015   return type;
7016 }
7017
7018 /* Given an object of type TYPE whose contents are at VALADDR and
7019    whose address in memory is ADDRESS, returns a revision of TYPE,
7020    which should be a non-dynamic-sized record, in which the variant
7021    part, if any, is replaced with the appropriate branch.  Looks
7022    for discriminant values in DVAL0, which can be NULL if the record
7023    contains the necessary discriminant values.  */
7024
7025 static struct type *
7026 to_record_with_fixed_variant_part (struct type *type, const gdb_byte *valaddr,
7027                                    CORE_ADDR address, struct value *dval0)
7028 {
7029   struct value *mark = value_mark ();
7030   struct value *dval;
7031   struct type *rtype;
7032   struct type *branch_type;
7033   int nfields = TYPE_NFIELDS (type);
7034   int variant_field = variant_field_index (type);
7035
7036   if (variant_field == -1)
7037     return type;
7038
7039   if (dval0 == NULL)
7040     dval = value_from_contents_and_address (type, valaddr, address);
7041   else
7042     dval = dval0;
7043
7044   rtype = alloc_type (TYPE_OBJFILE (type));
7045   TYPE_CODE (rtype) = TYPE_CODE_STRUCT;
7046   INIT_CPLUS_SPECIFIC (rtype);
7047   TYPE_NFIELDS (rtype) = nfields;
7048   TYPE_FIELDS (rtype) =
7049     (struct field *) TYPE_ALLOC (rtype, nfields * sizeof (struct field));
7050   memcpy (TYPE_FIELDS (rtype), TYPE_FIELDS (type),
7051           sizeof (struct field) * nfields);
7052   TYPE_NAME (rtype) = ada_type_name (type);
7053   TYPE_TAG_NAME (rtype) = NULL;
7054   TYPE_FIXED_INSTANCE (rtype) = 1;
7055   TYPE_LENGTH (rtype) = TYPE_LENGTH (type);
7056
7057   branch_type = to_fixed_variant_branch_type
7058     (TYPE_FIELD_TYPE (type, variant_field),
7059      cond_offset_host (valaddr,
7060                        TYPE_FIELD_BITPOS (type, variant_field)
7061                        / TARGET_CHAR_BIT),
7062      cond_offset_target (address,
7063                          TYPE_FIELD_BITPOS (type, variant_field)
7064                          / TARGET_CHAR_BIT), dval);
7065   if (branch_type == NULL)
7066     {
7067       int f;
7068       for (f = variant_field + 1; f < nfields; f += 1)
7069         TYPE_FIELDS (rtype)[f - 1] = TYPE_FIELDS (rtype)[f];
7070       TYPE_NFIELDS (rtype) -= 1;
7071     }
7072   else
7073     {
7074       TYPE_FIELD_TYPE (rtype, variant_field) = branch_type;
7075       TYPE_FIELD_NAME (rtype, variant_field) = "S";
7076       TYPE_FIELD_BITSIZE (rtype, variant_field) = 0;
7077       TYPE_LENGTH (rtype) += TYPE_LENGTH (branch_type);
7078     }
7079   TYPE_LENGTH (rtype) -= TYPE_LENGTH (TYPE_FIELD_TYPE (type, variant_field));
7080
7081   value_free_to_mark (mark);
7082   return rtype;
7083 }
7084
7085 /* An ordinary record type (with fixed-length fields) that describes
7086    the value at (TYPE0, VALADDR, ADDRESS) [see explanation at
7087    beginning of this section].   Any necessary discriminants' values
7088    should be in DVAL, a record value; it may be NULL if the object
7089    at ADDR itself contains any necessary discriminant values.
7090    Additionally, VALADDR and ADDRESS may also be NULL if no discriminant
7091    values from the record are needed.  Except in the case that DVAL,
7092    VALADDR, and ADDRESS are all 0 or NULL, a variant field (unless
7093    unchecked) is replaced by a particular branch of the variant.
7094
7095    NOTE: the case in which DVAL and VALADDR are NULL and ADDRESS is 0
7096    is questionable and may be removed.  It can arise during the
7097    processing of an unconstrained-array-of-record type where all the
7098    variant branches have exactly the same size.  This is because in
7099    such cases, the compiler does not bother to use the XVS convention
7100    when encoding the record.  I am currently dubious of this
7101    shortcut and suspect the compiler should be altered.  FIXME.  */
7102
7103 static struct type *
7104 to_fixed_record_type (struct type *type0, const gdb_byte *valaddr,
7105                       CORE_ADDR address, struct value *dval)
7106 {
7107   struct type *templ_type;
7108
7109   if (TYPE_FIXED_INSTANCE (type0))
7110     return type0;
7111
7112   templ_type = dynamic_template_type (type0);
7113
7114   if (templ_type != NULL)
7115     return template_to_fixed_record_type (templ_type, valaddr, address, dval);
7116   else if (variant_field_index (type0) >= 0)
7117     {
7118       if (dval == NULL && valaddr == NULL && address == 0)
7119         return type0;
7120       return to_record_with_fixed_variant_part (type0, valaddr, address,
7121                                                 dval);
7122     }
7123   else
7124     {
7125       TYPE_FIXED_INSTANCE (type0) = 1;
7126       return type0;
7127     }
7128
7129 }
7130
7131 /* An ordinary record type (with fixed-length fields) that describes
7132    the value at (VAR_TYPE0, VALADDR, ADDRESS), where VAR_TYPE0 is a
7133    union type.  Any necessary discriminants' values should be in DVAL,
7134    a record value.  That is, this routine selects the appropriate
7135    branch of the union at ADDR according to the discriminant value
7136    indicated in the union's type name.  Returns VAR_TYPE0 itself if
7137    it represents a variant subject to a pragma Unchecked_Union. */
7138
7139 static struct type *
7140 to_fixed_variant_branch_type (struct type *var_type0, const gdb_byte *valaddr,
7141                               CORE_ADDR address, struct value *dval)
7142 {
7143   int which;
7144   struct type *templ_type;
7145   struct type *var_type;
7146
7147   if (TYPE_CODE (var_type0) == TYPE_CODE_PTR)
7148     var_type = TYPE_TARGET_TYPE (var_type0);
7149   else
7150     var_type = var_type0;
7151
7152   templ_type = ada_find_parallel_type (var_type, "___XVU");
7153
7154   if (templ_type != NULL)
7155     var_type = templ_type;
7156
7157   if (is_unchecked_variant (var_type, value_type (dval)))
7158       return var_type0;
7159   which =
7160     ada_which_variant_applies (var_type,
7161                                value_type (dval), value_contents (dval));
7162
7163   if (which < 0)
7164     return empty_record (TYPE_OBJFILE (var_type));
7165   else if (is_dynamic_field (var_type, which))
7166     return to_fixed_record_type
7167       (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (var_type, which)),
7168        valaddr, address, dval);
7169   else if (variant_field_index (TYPE_FIELD_TYPE (var_type, which)) >= 0)
7170     return
7171       to_fixed_record_type
7172       (TYPE_FIELD_TYPE (var_type, which), valaddr, address, dval);
7173   else
7174     return TYPE_FIELD_TYPE (var_type, which);
7175 }
7176
7177 /* Assuming that TYPE0 is an array type describing the type of a value
7178    at ADDR, and that DVAL describes a record containing any
7179    discriminants used in TYPE0, returns a type for the value that
7180    contains no dynamic components (that is, no components whose sizes
7181    are determined by run-time quantities).  Unless IGNORE_TOO_BIG is
7182    true, gives an error message if the resulting type's size is over
7183    varsize_limit.  */
7184
7185 static struct type *
7186 to_fixed_array_type (struct type *type0, struct value *dval,
7187                      int ignore_too_big)
7188 {
7189   struct type *index_type_desc;
7190   struct type *result;
7191
7192   if (ada_is_packed_array_type (type0)  /* revisit? */
7193       || TYPE_FIXED_INSTANCE (type0))
7194     return type0;
7195
7196   index_type_desc = ada_find_parallel_type (type0, "___XA");
7197   if (index_type_desc == NULL)
7198     {
7199       struct type *elt_type0 = ada_check_typedef (TYPE_TARGET_TYPE (type0));
7200       /* NOTE: elt_type---the fixed version of elt_type0---should never
7201          depend on the contents of the array in properly constructed
7202          debugging data.  */
7203       /* Create a fixed version of the array element type.
7204          We're not providing the address of an element here,
7205          and thus the actual object value cannot be inspected to do
7206          the conversion.  This should not be a problem, since arrays of
7207          unconstrained objects are not allowed.  In particular, all
7208          the elements of an array of a tagged type should all be of
7209          the same type specified in the debugging info.  No need to
7210          consult the object tag.  */
7211       struct type *elt_type = ada_to_fixed_type (elt_type0, 0, 0, dval, 1);
7212
7213       if (elt_type0 == elt_type)
7214         result = type0;
7215       else
7216         result = create_array_type (alloc_type (TYPE_OBJFILE (type0)),
7217                                     elt_type, TYPE_INDEX_TYPE (type0));
7218     }
7219   else
7220     {
7221       int i;
7222       struct type *elt_type0;
7223
7224       elt_type0 = type0;
7225       for (i = TYPE_NFIELDS (index_type_desc); i > 0; i -= 1)
7226         elt_type0 = TYPE_TARGET_TYPE (elt_type0);
7227
7228       /* NOTE: result---the fixed version of elt_type0---should never
7229          depend on the contents of the array in properly constructed
7230          debugging data.  */
7231       /* Create a fixed version of the array element type.
7232          We're not providing the address of an element here,
7233          and thus the actual object value cannot be inspected to do
7234          the conversion.  This should not be a problem, since arrays of
7235          unconstrained objects are not allowed.  In particular, all
7236          the elements of an array of a tagged type should all be of
7237          the same type specified in the debugging info.  No need to
7238          consult the object tag.  */
7239       result =
7240         ada_to_fixed_type (ada_check_typedef (elt_type0), 0, 0, dval, 1);
7241       for (i = TYPE_NFIELDS (index_type_desc) - 1; i >= 0; i -= 1)
7242         {
7243           struct type *range_type =
7244             to_fixed_range_type (TYPE_FIELD_NAME (index_type_desc, i),
7245                                  dval, TYPE_OBJFILE (type0));
7246           result = create_array_type (alloc_type (TYPE_OBJFILE (type0)),
7247                                       result, range_type);
7248         }
7249       if (!ignore_too_big && TYPE_LENGTH (result) > varsize_limit)
7250         error (_("array type with dynamic size is larger than varsize-limit"));
7251     }
7252
7253   TYPE_FIXED_INSTANCE (result) = 1;
7254   return result;
7255 }
7256
7257
7258 /* A standard type (containing no dynamically sized components)
7259    corresponding to TYPE for the value (TYPE, VALADDR, ADDRESS)
7260    DVAL describes a record containing any discriminants used in TYPE0,
7261    and may be NULL if there are none, or if the object of type TYPE at
7262    ADDRESS or in VALADDR contains these discriminants.
7263    
7264    If CHECK_TAG is not null, in the case of tagged types, this function
7265    attempts to locate the object's tag and use it to compute the actual
7266    type.  However, when ADDRESS is null, we cannot use it to determine the
7267    location of the tag, and therefore compute the tagged type's actual type.
7268    So we return the tagged type without consulting the tag.  */
7269    
7270 static struct type *
7271 ada_to_fixed_type_1 (struct type *type, const gdb_byte *valaddr,
7272                    CORE_ADDR address, struct value *dval, int check_tag)
7273 {
7274   type = ada_check_typedef (type);
7275   switch (TYPE_CODE (type))
7276     {
7277     default:
7278       return type;
7279     case TYPE_CODE_STRUCT:
7280       {
7281         struct type *static_type = to_static_fixed_type (type);
7282         struct type *fixed_record_type =
7283           to_fixed_record_type (type, valaddr, address, NULL);
7284         /* If STATIC_TYPE is a tagged type and we know the object's address,
7285            then we can determine its tag, and compute the object's actual
7286            type from there. Note that we have to use the fixed record
7287            type (the parent part of the record may have dynamic fields
7288            and the way the location of _tag is expressed may depend on
7289            them).  */
7290
7291         if (check_tag && address != 0 && ada_is_tagged_type (static_type, 0))
7292           {
7293             struct type *real_type =
7294               type_from_tag (value_tag_from_contents_and_address
7295                              (fixed_record_type,
7296                               valaddr,
7297                               address));
7298             if (real_type != NULL)
7299               return to_fixed_record_type (real_type, valaddr, address, NULL);
7300           }
7301
7302         /* Check to see if there is a parallel ___XVZ variable.
7303            If there is, then it provides the actual size of our type.  */
7304         else if (ada_type_name (fixed_record_type) != NULL)
7305           {
7306             char *name = ada_type_name (fixed_record_type);
7307             char *xvz_name = alloca (strlen (name) + 7 /* "___XVZ\0" */);
7308             int xvz_found = 0;
7309             LONGEST size;
7310
7311             sprintf (xvz_name, "%s___XVZ", name);
7312             size = get_int_var_value (xvz_name, &xvz_found);
7313             if (xvz_found && TYPE_LENGTH (fixed_record_type) != size)
7314               {
7315                 fixed_record_type = copy_type (fixed_record_type);
7316                 TYPE_LENGTH (fixed_record_type) = size;
7317
7318                 /* The FIXED_RECORD_TYPE may have be a stub.  We have
7319                    observed this when the debugging info is STABS, and
7320                    apparently it is something that is hard to fix.
7321
7322                    In practice, we don't need the actual type definition
7323                    at all, because the presence of the XVZ variable allows us
7324                    to assume that there must be a XVS type as well, which we
7325                    should be able to use later, when we need the actual type
7326                    definition.
7327
7328                    In the meantime, pretend that the "fixed" type we are
7329                    returning is NOT a stub, because this can cause trouble
7330                    when using this type to create new types targeting it.
7331                    Indeed, the associated creation routines often check
7332                    whether the target type is a stub and will try to replace
7333                    it, thus using a type with the wrong size. This, in turn,
7334                    might cause the new type to have the wrong size too.
7335                    Consider the case of an array, for instance, where the size
7336                    of the array is computed from the number of elements in
7337                    our array multiplied by the size of its element.  */
7338                 TYPE_STUB (fixed_record_type) = 0;
7339               }
7340           }
7341         return fixed_record_type;
7342       }
7343     case TYPE_CODE_ARRAY:
7344       return to_fixed_array_type (type, dval, 1);
7345     case TYPE_CODE_UNION:
7346       if (dval == NULL)
7347         return type;
7348       else
7349         return to_fixed_variant_branch_type (type, valaddr, address, dval);
7350     }
7351 }
7352
7353 /* The same as ada_to_fixed_type_1, except that it preserves the type
7354    if it is a TYPE_CODE_TYPEDEF of a type that is already fixed.
7355    ada_to_fixed_type_1 would return the type referenced by TYPE.  */
7356
7357 struct type *
7358 ada_to_fixed_type (struct type *type, const gdb_byte *valaddr,
7359                    CORE_ADDR address, struct value *dval, int check_tag)
7360
7361 {
7362   struct type *fixed_type =
7363     ada_to_fixed_type_1 (type, valaddr, address, dval, check_tag);
7364
7365   if (TYPE_CODE (type) == TYPE_CODE_TYPEDEF
7366       && TYPE_TARGET_TYPE (type) == fixed_type)
7367     return type;
7368
7369   return fixed_type;
7370 }
7371
7372 /* A standard (static-sized) type corresponding as well as possible to
7373    TYPE0, but based on no runtime data.  */
7374
7375 static struct type *
7376 to_static_fixed_type (struct type *type0)
7377 {
7378   struct type *type;
7379
7380   if (type0 == NULL)
7381     return NULL;
7382
7383   if (TYPE_FIXED_INSTANCE (type0))
7384     return type0;
7385
7386   type0 = ada_check_typedef (type0);
7387
7388   switch (TYPE_CODE (type0))
7389     {
7390     default:
7391       return type0;
7392     case TYPE_CODE_STRUCT:
7393       type = dynamic_template_type (type0);
7394       if (type != NULL)
7395         return template_to_static_fixed_type (type);
7396       else
7397         return template_to_static_fixed_type (type0);
7398     case TYPE_CODE_UNION:
7399       type = ada_find_parallel_type (type0, "___XVU");
7400       if (type != NULL)
7401         return template_to_static_fixed_type (type);
7402       else
7403         return template_to_static_fixed_type (type0);
7404     }
7405 }
7406
7407 /* A static approximation of TYPE with all type wrappers removed.  */
7408
7409 static struct type *
7410 static_unwrap_type (struct type *type)
7411 {
7412   if (ada_is_aligner_type (type))
7413     {
7414       struct type *type1 = TYPE_FIELD_TYPE (ada_check_typedef (type), 0);
7415       if (ada_type_name (type1) == NULL)
7416         TYPE_NAME (type1) = ada_type_name (type);
7417
7418       return static_unwrap_type (type1);
7419     }
7420   else
7421     {
7422       struct type *raw_real_type = ada_get_base_type (type);
7423       if (raw_real_type == type)
7424         return type;
7425       else
7426         return to_static_fixed_type (raw_real_type);
7427     }
7428 }
7429
7430 /* In some cases, incomplete and private types require
7431    cross-references that are not resolved as records (for example,
7432       type Foo;
7433       type FooP is access Foo;
7434       V: FooP;
7435       type Foo is array ...;
7436    ).  In these cases, since there is no mechanism for producing
7437    cross-references to such types, we instead substitute for FooP a
7438    stub enumeration type that is nowhere resolved, and whose tag is
7439    the name of the actual type.  Call these types "non-record stubs".  */
7440
7441 /* A type equivalent to TYPE that is not a non-record stub, if one
7442    exists, otherwise TYPE.  */
7443
7444 struct type *
7445 ada_check_typedef (struct type *type)
7446 {
7447   if (type == NULL)
7448     return NULL;
7449
7450   CHECK_TYPEDEF (type);
7451   if (type == NULL || TYPE_CODE (type) != TYPE_CODE_ENUM
7452       || !TYPE_STUB (type)
7453       || TYPE_TAG_NAME (type) == NULL)
7454     return type;
7455   else
7456     {
7457       char *name = TYPE_TAG_NAME (type);
7458       struct type *type1 = ada_find_any_type (name);
7459       return (type1 == NULL) ? type : type1;
7460     }
7461 }
7462
7463 /* A value representing the data at VALADDR/ADDRESS as described by
7464    type TYPE0, but with a standard (static-sized) type that correctly
7465    describes it.  If VAL0 is not NULL and TYPE0 already is a standard
7466    type, then return VAL0 [this feature is simply to avoid redundant
7467    creation of struct values].  */
7468
7469 static struct value *
7470 ada_to_fixed_value_create (struct type *type0, CORE_ADDR address,
7471                            struct value *val0)
7472 {
7473   struct type *type = ada_to_fixed_type (type0, 0, address, NULL, 1);
7474   if (type == type0 && val0 != NULL)
7475     return val0;
7476   else
7477     return value_from_contents_and_address (type, 0, address);
7478 }
7479
7480 /* A value representing VAL, but with a standard (static-sized) type
7481    that correctly describes it.  Does not necessarily create a new
7482    value.  */
7483
7484 static struct value *
7485 ada_to_fixed_value (struct value *val)
7486 {
7487   return ada_to_fixed_value_create (value_type (val),
7488                                     VALUE_ADDRESS (val) + value_offset (val),
7489                                     val);
7490 }
7491
7492 /* A value representing VAL, but with a standard (static-sized) type
7493    chosen to approximate the real type of VAL as well as possible, but
7494    without consulting any runtime values.  For Ada dynamic-sized
7495    types, therefore, the type of the result is likely to be inaccurate.  */
7496
7497 static struct value *
7498 ada_to_static_fixed_value (struct value *val)
7499 {
7500   struct type *type =
7501     to_static_fixed_type (static_unwrap_type (value_type (val)));
7502   if (type == value_type (val))
7503     return val;
7504   else
7505     return coerce_unspec_val_to_type (val, type);
7506 }
7507 \f
7508
7509 /* Attributes */
7510
7511 /* Table mapping attribute numbers to names.
7512    NOTE: Keep up to date with enum ada_attribute definition in ada-lang.h.  */
7513
7514 static const char *attribute_names[] = {
7515   "<?>",
7516
7517   "first",
7518   "last",
7519   "length",
7520   "image",
7521   "max",
7522   "min",
7523   "modulus",
7524   "pos",
7525   "size",
7526   "tag",
7527   "val",
7528   0
7529 };
7530
7531 const char *
7532 ada_attribute_name (enum exp_opcode n)
7533 {
7534   if (n >= OP_ATR_FIRST && n <= (int) OP_ATR_VAL)
7535     return attribute_names[n - OP_ATR_FIRST + 1];
7536   else
7537     return attribute_names[0];
7538 }
7539
7540 /* Evaluate the 'POS attribute applied to ARG.  */
7541
7542 static LONGEST
7543 pos_atr (struct value *arg)
7544 {
7545   struct value *val = coerce_ref (arg);
7546   struct type *type = value_type (val);
7547
7548   if (!discrete_type_p (type))
7549     error (_("'POS only defined on discrete types"));
7550
7551   if (TYPE_CODE (type) == TYPE_CODE_ENUM)
7552     {
7553       int i;
7554       LONGEST v = value_as_long (val);
7555
7556       for (i = 0; i < TYPE_NFIELDS (type); i += 1)
7557         {
7558           if (v == TYPE_FIELD_BITPOS (type, i))
7559             return i;
7560         }
7561       error (_("enumeration value is invalid: can't find 'POS"));
7562     }
7563   else
7564     return value_as_long (val);
7565 }
7566
7567 static struct value *
7568 value_pos_atr (struct type *type, struct value *arg)
7569 {
7570   return value_from_longest (type, pos_atr (arg));
7571 }
7572
7573 /* Evaluate the TYPE'VAL attribute applied to ARG.  */
7574
7575 static struct value *
7576 value_val_atr (struct type *type, struct value *arg)
7577 {
7578   if (!discrete_type_p (type))
7579     error (_("'VAL only defined on discrete types"));
7580   if (!integer_type_p (value_type (arg)))
7581     error (_("'VAL requires integral argument"));
7582
7583   if (TYPE_CODE (type) == TYPE_CODE_ENUM)
7584     {
7585       long pos = value_as_long (arg);
7586       if (pos < 0 || pos >= TYPE_NFIELDS (type))
7587         error (_("argument to 'VAL out of range"));
7588       return value_from_longest (type, TYPE_FIELD_BITPOS (type, pos));
7589     }
7590   else
7591     return value_from_longest (type, value_as_long (arg));
7592 }
7593 \f
7594
7595                                 /* Evaluation */
7596
7597 /* True if TYPE appears to be an Ada character type.
7598    [At the moment, this is true only for Character and Wide_Character;
7599    It is a heuristic test that could stand improvement].  */
7600
7601 int
7602 ada_is_character_type (struct type *type)
7603 {
7604   const char *name;
7605
7606   /* If the type code says it's a character, then assume it really is,
7607      and don't check any further.  */
7608   if (TYPE_CODE (type) == TYPE_CODE_CHAR)
7609     return 1;
7610   
7611   /* Otherwise, assume it's a character type iff it is a discrete type
7612      with a known character type name.  */
7613   name = ada_type_name (type);
7614   return (name != NULL
7615           && (TYPE_CODE (type) == TYPE_CODE_INT
7616               || TYPE_CODE (type) == TYPE_CODE_RANGE)
7617           && (strcmp (name, "character") == 0
7618               || strcmp (name, "wide_character") == 0
7619               || strcmp (name, "wide_wide_character") == 0
7620               || strcmp (name, "unsigned char") == 0));
7621 }
7622
7623 /* True if TYPE appears to be an Ada string type.  */
7624
7625 int
7626 ada_is_string_type (struct type *type)
7627 {
7628   type = ada_check_typedef (type);
7629   if (type != NULL
7630       && TYPE_CODE (type) != TYPE_CODE_PTR
7631       && (ada_is_simple_array_type (type)
7632           || ada_is_array_descriptor_type (type))
7633       && ada_array_arity (type) == 1)
7634     {
7635       struct type *elttype = ada_array_element_type (type, 1);
7636
7637       return ada_is_character_type (elttype);
7638     }
7639   else
7640     return 0;
7641 }
7642
7643
7644 /* True if TYPE is a struct type introduced by the compiler to force the
7645    alignment of a value.  Such types have a single field with a
7646    distinctive name.  */
7647
7648 int
7649 ada_is_aligner_type (struct type *type)
7650 {
7651   type = ada_check_typedef (type);
7652
7653   /* If we can find a parallel XVS type, then the XVS type should
7654      be used instead of this type.  And hence, this is not an aligner
7655      type.  */
7656   if (ada_find_parallel_type (type, "___XVS") != NULL)
7657     return 0;
7658
7659   return (TYPE_CODE (type) == TYPE_CODE_STRUCT
7660           && TYPE_NFIELDS (type) == 1
7661           && strcmp (TYPE_FIELD_NAME (type, 0), "F") == 0);
7662 }
7663
7664 /* If there is an ___XVS-convention type parallel to SUBTYPE, return
7665    the parallel type.  */
7666
7667 struct type *
7668 ada_get_base_type (struct type *raw_type)
7669 {
7670   struct type *real_type_namer;
7671   struct type *raw_real_type;
7672
7673   if (raw_type == NULL || TYPE_CODE (raw_type) != TYPE_CODE_STRUCT)
7674     return raw_type;
7675
7676   real_type_namer = ada_find_parallel_type (raw_type, "___XVS");
7677   if (real_type_namer == NULL
7678       || TYPE_CODE (real_type_namer) != TYPE_CODE_STRUCT
7679       || TYPE_NFIELDS (real_type_namer) != 1)
7680     return raw_type;
7681
7682   raw_real_type = ada_find_any_type (TYPE_FIELD_NAME (real_type_namer, 0));
7683   if (raw_real_type == NULL)
7684     return raw_type;
7685   else
7686     return raw_real_type;
7687 }
7688
7689 /* The type of value designated by TYPE, with all aligners removed.  */
7690
7691 struct type *
7692 ada_aligned_type (struct type *type)
7693 {
7694   if (ada_is_aligner_type (type))
7695     return ada_aligned_type (TYPE_FIELD_TYPE (type, 0));
7696   else
7697     return ada_get_base_type (type);
7698 }
7699
7700
7701 /* The address of the aligned value in an object at address VALADDR
7702    having type TYPE.  Assumes ada_is_aligner_type (TYPE).  */
7703
7704 const gdb_byte *
7705 ada_aligned_value_addr (struct type *type, const gdb_byte *valaddr)
7706 {
7707   if (ada_is_aligner_type (type))
7708     return ada_aligned_value_addr (TYPE_FIELD_TYPE (type, 0),
7709                                    valaddr +
7710                                    TYPE_FIELD_BITPOS (type,
7711                                                       0) / TARGET_CHAR_BIT);
7712   else
7713     return valaddr;
7714 }
7715
7716
7717
7718 /* The printed representation of an enumeration literal with encoded
7719    name NAME.  The value is good to the next call of ada_enum_name.  */
7720 const char *
7721 ada_enum_name (const char *name)
7722 {
7723   static char *result;
7724   static size_t result_len = 0;
7725   char *tmp;
7726
7727   /* First, unqualify the enumeration name:
7728      1. Search for the last '.' character.  If we find one, then skip
7729      all the preceeding characters, the unqualified name starts
7730      right after that dot.
7731      2. Otherwise, we may be debugging on a target where the compiler
7732      translates dots into "__".  Search forward for double underscores,
7733      but stop searching when we hit an overloading suffix, which is
7734      of the form "__" followed by digits.  */
7735
7736   tmp = strrchr (name, '.');
7737   if (tmp != NULL)
7738     name = tmp + 1;
7739   else
7740     {
7741       while ((tmp = strstr (name, "__")) != NULL)
7742         {
7743           if (isdigit (tmp[2]))
7744             break;
7745           else
7746             name = tmp + 2;
7747         }
7748     }
7749
7750   if (name[0] == 'Q')
7751     {
7752       int v;
7753       if (name[1] == 'U' || name[1] == 'W')
7754         {
7755           if (sscanf (name + 2, "%x", &v) != 1)
7756             return name;
7757         }
7758       else
7759         return name;
7760
7761       GROW_VECT (result, result_len, 16);
7762       if (isascii (v) && isprint (v))
7763         sprintf (result, "'%c'", v);
7764       else if (name[1] == 'U')
7765         sprintf (result, "[\"%02x\"]", v);
7766       else
7767         sprintf (result, "[\"%04x\"]", v);
7768
7769       return result;
7770     }
7771   else
7772     {
7773       tmp = strstr (name, "__");
7774       if (tmp == NULL)
7775         tmp = strstr (name, "$");
7776       if (tmp != NULL)
7777         {
7778           GROW_VECT (result, result_len, tmp - name + 1);
7779           strncpy (result, name, tmp - name);
7780           result[tmp - name] = '\0';
7781           return result;
7782         }
7783
7784       return name;
7785     }
7786 }
7787
7788 static struct value *
7789 evaluate_subexp (struct type *expect_type, struct expression *exp, int *pos,
7790                  enum noside noside)
7791 {
7792   return (*exp->language_defn->la_exp_desc->evaluate_exp)
7793     (expect_type, exp, pos, noside);
7794 }
7795
7796 /* Evaluate the subexpression of EXP starting at *POS as for
7797    evaluate_type, updating *POS to point just past the evaluated
7798    expression.  */
7799
7800 static struct value *
7801 evaluate_subexp_type (struct expression *exp, int *pos)
7802 {
7803   return (*exp->language_defn->la_exp_desc->evaluate_exp)
7804     (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
7805 }
7806
7807 /* If VAL is wrapped in an aligner or subtype wrapper, return the
7808    value it wraps.  */
7809
7810 static struct value *
7811 unwrap_value (struct value *val)
7812 {
7813   struct type *type = ada_check_typedef (value_type (val));
7814   if (ada_is_aligner_type (type))
7815     {
7816       struct value *v = ada_value_struct_elt (val, "F", 0);
7817       struct type *val_type = ada_check_typedef (value_type (v));
7818       if (ada_type_name (val_type) == NULL)
7819         TYPE_NAME (val_type) = ada_type_name (type);
7820
7821       return unwrap_value (v);
7822     }
7823   else
7824     {
7825       struct type *raw_real_type =
7826         ada_check_typedef (ada_get_base_type (type));
7827
7828       if (type == raw_real_type)
7829         return val;
7830
7831       return
7832         coerce_unspec_val_to_type
7833         (val, ada_to_fixed_type (raw_real_type, 0,
7834                                  VALUE_ADDRESS (val) + value_offset (val),
7835                                  NULL, 1));
7836     }
7837 }
7838
7839 static struct value *
7840 cast_to_fixed (struct type *type, struct value *arg)
7841 {
7842   LONGEST val;
7843
7844   if (type == value_type (arg))
7845     return arg;
7846   else if (ada_is_fixed_point_type (value_type (arg)))
7847     val = ada_float_to_fixed (type,
7848                               ada_fixed_to_float (value_type (arg),
7849                                                   value_as_long (arg)));
7850   else
7851     {
7852       DOUBLEST argd = value_as_double (arg);
7853       val = ada_float_to_fixed (type, argd);
7854     }
7855
7856   return value_from_longest (type, val);
7857 }
7858
7859 static struct value *
7860 cast_from_fixed (struct type *type, struct value *arg)
7861 {
7862   DOUBLEST val = ada_fixed_to_float (value_type (arg),
7863                                      value_as_long (arg));
7864   return value_from_double (type, val);
7865 }
7866
7867 /* Coerce VAL as necessary for assignment to an lval of type TYPE, and
7868    return the converted value.  */
7869
7870 static struct value *
7871 coerce_for_assign (struct type *type, struct value *val)
7872 {
7873   struct type *type2 = value_type (val);
7874   if (type == type2)
7875     return val;
7876
7877   type2 = ada_check_typedef (type2);
7878   type = ada_check_typedef (type);
7879
7880   if (TYPE_CODE (type2) == TYPE_CODE_PTR
7881       && TYPE_CODE (type) == TYPE_CODE_ARRAY)
7882     {
7883       val = ada_value_ind (val);
7884       type2 = value_type (val);
7885     }
7886
7887   if (TYPE_CODE (type2) == TYPE_CODE_ARRAY
7888       && TYPE_CODE (type) == TYPE_CODE_ARRAY)
7889     {
7890       if (TYPE_LENGTH (type2) != TYPE_LENGTH (type)
7891           || TYPE_LENGTH (TYPE_TARGET_TYPE (type2))
7892           != TYPE_LENGTH (TYPE_TARGET_TYPE (type2)))
7893         error (_("Incompatible types in assignment"));
7894       deprecated_set_value_type (val, type);
7895     }
7896   return val;
7897 }
7898
7899 static struct value *
7900 ada_value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op)
7901 {
7902   struct value *val;
7903   struct type *type1, *type2;
7904   LONGEST v, v1, v2;
7905
7906   arg1 = coerce_ref (arg1);
7907   arg2 = coerce_ref (arg2);
7908   type1 = base_type (ada_check_typedef (value_type (arg1)));
7909   type2 = base_type (ada_check_typedef (value_type (arg2)));
7910
7911   if (TYPE_CODE (type1) != TYPE_CODE_INT
7912       || TYPE_CODE (type2) != TYPE_CODE_INT)
7913     return value_binop (arg1, arg2, op);
7914
7915   switch (op)
7916     {
7917     case BINOP_MOD:
7918     case BINOP_DIV:
7919     case BINOP_REM:
7920       break;
7921     default:
7922       return value_binop (arg1, arg2, op);
7923     }
7924
7925   v2 = value_as_long (arg2);
7926   if (v2 == 0)
7927     error (_("second operand of %s must not be zero."), op_string (op));
7928
7929   if (TYPE_UNSIGNED (type1) || op == BINOP_MOD)
7930     return value_binop (arg1, arg2, op);
7931
7932   v1 = value_as_long (arg1);
7933   switch (op)
7934     {
7935     case BINOP_DIV:
7936       v = v1 / v2;
7937       if (!TRUNCATION_TOWARDS_ZERO && v1 * (v1 % v2) < 0)
7938         v += v > 0 ? -1 : 1;
7939       break;
7940     case BINOP_REM:
7941       v = v1 % v2;
7942       if (v * v1 < 0)
7943         v -= v2;
7944       break;
7945     default:
7946       /* Should not reach this point.  */
7947       v = 0;
7948     }
7949
7950   val = allocate_value (type1);
7951   store_unsigned_integer (value_contents_raw (val),
7952                           TYPE_LENGTH (value_type (val)), v);
7953   return val;
7954 }
7955
7956 static int
7957 ada_value_equal (struct value *arg1, struct value *arg2)
7958 {
7959   if (ada_is_direct_array_type (value_type (arg1))
7960       || ada_is_direct_array_type (value_type (arg2)))
7961     {
7962       /* Automatically dereference any array reference before
7963          we attempt to perform the comparison.  */
7964       arg1 = ada_coerce_ref (arg1);
7965       arg2 = ada_coerce_ref (arg2);
7966       
7967       arg1 = ada_coerce_to_simple_array (arg1);
7968       arg2 = ada_coerce_to_simple_array (arg2);
7969       if (TYPE_CODE (value_type (arg1)) != TYPE_CODE_ARRAY
7970           || TYPE_CODE (value_type (arg2)) != TYPE_CODE_ARRAY)
7971         error (_("Attempt to compare array with non-array"));
7972       /* FIXME: The following works only for types whose
7973          representations use all bits (no padding or undefined bits)
7974          and do not have user-defined equality.  */
7975       return
7976         TYPE_LENGTH (value_type (arg1)) == TYPE_LENGTH (value_type (arg2))
7977         && memcmp (value_contents (arg1), value_contents (arg2),
7978                    TYPE_LENGTH (value_type (arg1))) == 0;
7979     }
7980   return value_equal (arg1, arg2);
7981 }
7982
7983 /* Total number of component associations in the aggregate starting at
7984    index PC in EXP.  Assumes that index PC is the start of an
7985    OP_AGGREGATE. */
7986
7987 static int
7988 num_component_specs (struct expression *exp, int pc)
7989 {
7990   int n, m, i;
7991   m = exp->elts[pc + 1].longconst;
7992   pc += 3;
7993   n = 0;
7994   for (i = 0; i < m; i += 1)
7995     {
7996       switch (exp->elts[pc].opcode) 
7997         {
7998         default:
7999           n += 1;
8000           break;
8001         case OP_CHOICES:
8002           n += exp->elts[pc + 1].longconst;
8003           break;
8004         }
8005       ada_evaluate_subexp (NULL, exp, &pc, EVAL_SKIP);
8006     }
8007   return n;
8008 }
8009
8010 /* Assign the result of evaluating EXP starting at *POS to the INDEXth 
8011    component of LHS (a simple array or a record), updating *POS past
8012    the expression, assuming that LHS is contained in CONTAINER.  Does
8013    not modify the inferior's memory, nor does it modify LHS (unless
8014    LHS == CONTAINER).  */
8015
8016 static void
8017 assign_component (struct value *container, struct value *lhs, LONGEST index,
8018                   struct expression *exp, int *pos)
8019 {
8020   struct value *mark = value_mark ();
8021   struct value *elt;
8022   if (TYPE_CODE (value_type (lhs)) == TYPE_CODE_ARRAY)
8023     {
8024       struct value *index_val = value_from_longest (builtin_type_int32, index);
8025       elt = unwrap_value (ada_value_subscript (lhs, 1, &index_val));
8026     }
8027   else
8028     {
8029       elt = ada_index_struct_field (index, lhs, 0, value_type (lhs));
8030       elt = ada_to_fixed_value (unwrap_value (elt));
8031     }
8032
8033   if (exp->elts[*pos].opcode == OP_AGGREGATE)
8034     assign_aggregate (container, elt, exp, pos, EVAL_NORMAL);
8035   else
8036     value_assign_to_component (container, elt, 
8037                                ada_evaluate_subexp (NULL, exp, pos, 
8038                                                     EVAL_NORMAL));
8039
8040   value_free_to_mark (mark);
8041 }
8042
8043 /* Assuming that LHS represents an lvalue having a record or array
8044    type, and EXP->ELTS[*POS] is an OP_AGGREGATE, evaluate an assignment
8045    of that aggregate's value to LHS, advancing *POS past the
8046    aggregate.  NOSIDE is as for evaluate_subexp.  CONTAINER is an
8047    lvalue containing LHS (possibly LHS itself).  Does not modify
8048    the inferior's memory, nor does it modify the contents of 
8049    LHS (unless == CONTAINER).  Returns the modified CONTAINER. */
8050
8051 static struct value *
8052 assign_aggregate (struct value *container, 
8053                   struct value *lhs, struct expression *exp, 
8054                   int *pos, enum noside noside)
8055 {
8056   struct type *lhs_type;
8057   int n = exp->elts[*pos+1].longconst;
8058   LONGEST low_index, high_index;
8059   int num_specs;
8060   LONGEST *indices;
8061   int max_indices, num_indices;
8062   int is_array_aggregate;
8063   int i;
8064   struct value *mark = value_mark ();
8065
8066   *pos += 3;
8067   if (noside != EVAL_NORMAL)
8068     {
8069       int i;
8070       for (i = 0; i < n; i += 1)
8071         ada_evaluate_subexp (NULL, exp, pos, noside);
8072       return container;
8073     }
8074
8075   container = ada_coerce_ref (container);
8076   if (ada_is_direct_array_type (value_type (container)))
8077     container = ada_coerce_to_simple_array (container);
8078   lhs = ada_coerce_ref (lhs);
8079   if (!deprecated_value_modifiable (lhs))
8080     error (_("Left operand of assignment is not a modifiable lvalue."));
8081
8082   lhs_type = value_type (lhs);
8083   if (ada_is_direct_array_type (lhs_type))
8084     {
8085       lhs = ada_coerce_to_simple_array (lhs);
8086       lhs_type = value_type (lhs);
8087       low_index = TYPE_ARRAY_LOWER_BOUND_VALUE (lhs_type);
8088       high_index = TYPE_ARRAY_UPPER_BOUND_VALUE (lhs_type);
8089       is_array_aggregate = 1;
8090     }
8091   else if (TYPE_CODE (lhs_type) == TYPE_CODE_STRUCT)
8092     {
8093       low_index = 0;
8094       high_index = num_visible_fields (lhs_type) - 1;
8095       is_array_aggregate = 0;
8096     }
8097   else
8098     error (_("Left-hand side must be array or record."));
8099
8100   num_specs = num_component_specs (exp, *pos - 3);
8101   max_indices = 4 * num_specs + 4;
8102   indices = alloca (max_indices * sizeof (indices[0]));
8103   indices[0] = indices[1] = low_index - 1;
8104   indices[2] = indices[3] = high_index + 1;
8105   num_indices = 4;
8106
8107   for (i = 0; i < n; i += 1)
8108     {
8109       switch (exp->elts[*pos].opcode)
8110         {
8111         case OP_CHOICES:
8112           aggregate_assign_from_choices (container, lhs, exp, pos, indices, 
8113                                          &num_indices, max_indices,
8114                                          low_index, high_index);
8115           break;
8116         case OP_POSITIONAL:
8117           aggregate_assign_positional (container, lhs, exp, pos, indices,
8118                                        &num_indices, max_indices,
8119                                        low_index, high_index);
8120           break;
8121         case OP_OTHERS:
8122           if (i != n-1)
8123             error (_("Misplaced 'others' clause"));
8124           aggregate_assign_others (container, lhs, exp, pos, indices, 
8125                                    num_indices, low_index, high_index);
8126           break;
8127         default:
8128           error (_("Internal error: bad aggregate clause"));
8129         }
8130     }
8131
8132   return container;
8133 }
8134               
8135 /* Assign into the component of LHS indexed by the OP_POSITIONAL
8136    construct at *POS, updating *POS past the construct, given that
8137    the positions are relative to lower bound LOW, where HIGH is the 
8138    upper bound.  Record the position in INDICES[0 .. MAX_INDICES-1]
8139    updating *NUM_INDICES as needed.  CONTAINER is as for
8140    assign_aggregate. */
8141 static void
8142 aggregate_assign_positional (struct value *container,
8143                              struct value *lhs, struct expression *exp,
8144                              int *pos, LONGEST *indices, int *num_indices,
8145                              int max_indices, LONGEST low, LONGEST high) 
8146 {
8147   LONGEST ind = longest_to_int (exp->elts[*pos + 1].longconst) + low;
8148   
8149   if (ind - 1 == high)
8150     warning (_("Extra components in aggregate ignored."));
8151   if (ind <= high)
8152     {
8153       add_component_interval (ind, ind, indices, num_indices, max_indices);
8154       *pos += 3;
8155       assign_component (container, lhs, ind, exp, pos);
8156     }
8157   else
8158     ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
8159 }
8160
8161 /* Assign into the components of LHS indexed by the OP_CHOICES
8162    construct at *POS, updating *POS past the construct, given that
8163    the allowable indices are LOW..HIGH.  Record the indices assigned
8164    to in INDICES[0 .. MAX_INDICES-1], updating *NUM_INDICES as
8165    needed.  CONTAINER is as for assign_aggregate. */
8166 static void
8167 aggregate_assign_from_choices (struct value *container,
8168                                struct value *lhs, struct expression *exp,
8169                                int *pos, LONGEST *indices, int *num_indices,
8170                                int max_indices, LONGEST low, LONGEST high) 
8171 {
8172   int j;
8173   int n_choices = longest_to_int (exp->elts[*pos+1].longconst);
8174   int choice_pos, expr_pc;
8175   int is_array = ada_is_direct_array_type (value_type (lhs));
8176
8177   choice_pos = *pos += 3;
8178
8179   for (j = 0; j < n_choices; j += 1)
8180     ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
8181   expr_pc = *pos;
8182   ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
8183   
8184   for (j = 0; j < n_choices; j += 1)
8185     {
8186       LONGEST lower, upper;
8187       enum exp_opcode op = exp->elts[choice_pos].opcode;
8188       if (op == OP_DISCRETE_RANGE)
8189         {
8190           choice_pos += 1;
8191           lower = value_as_long (ada_evaluate_subexp (NULL, exp, pos,
8192                                                       EVAL_NORMAL));
8193           upper = value_as_long (ada_evaluate_subexp (NULL, exp, pos, 
8194                                                       EVAL_NORMAL));
8195         }
8196       else if (is_array)
8197         {
8198           lower = value_as_long (ada_evaluate_subexp (NULL, exp, &choice_pos, 
8199                                                       EVAL_NORMAL));
8200           upper = lower;
8201         }
8202       else
8203         {
8204           int ind;
8205           char *name;
8206           switch (op)
8207             {
8208             case OP_NAME:
8209               name = &exp->elts[choice_pos + 2].string;
8210               break;
8211             case OP_VAR_VALUE:
8212               name = SYMBOL_NATURAL_NAME (exp->elts[choice_pos + 2].symbol);
8213               break;
8214             default:
8215               error (_("Invalid record component association."));
8216             }
8217           ada_evaluate_subexp (NULL, exp, &choice_pos, EVAL_SKIP);
8218           ind = 0;
8219           if (! find_struct_field (name, value_type (lhs), 0, 
8220                                    NULL, NULL, NULL, NULL, &ind))
8221             error (_("Unknown component name: %s."), name);
8222           lower = upper = ind;
8223         }
8224
8225       if (lower <= upper && (lower < low || upper > high))
8226         error (_("Index in component association out of bounds."));
8227
8228       add_component_interval (lower, upper, indices, num_indices,
8229                               max_indices);
8230       while (lower <= upper)
8231         {
8232           int pos1;
8233           pos1 = expr_pc;
8234           assign_component (container, lhs, lower, exp, &pos1);
8235           lower += 1;
8236         }
8237     }
8238 }
8239
8240 /* Assign the value of the expression in the OP_OTHERS construct in
8241    EXP at *POS into the components of LHS indexed from LOW .. HIGH that
8242    have not been previously assigned.  The index intervals already assigned
8243    are in INDICES[0 .. NUM_INDICES-1].  Updates *POS to after the 
8244    OP_OTHERS clause.  CONTAINER is as for assign_aggregate*/
8245 static void
8246 aggregate_assign_others (struct value *container,
8247                          struct value *lhs, struct expression *exp,
8248                          int *pos, LONGEST *indices, int num_indices,
8249                          LONGEST low, LONGEST high) 
8250 {
8251   int i;
8252   int expr_pc = *pos+1;
8253   
8254   for (i = 0; i < num_indices - 2; i += 2)
8255     {
8256       LONGEST ind;
8257       for (ind = indices[i + 1] + 1; ind < indices[i + 2]; ind += 1)
8258         {
8259           int pos;
8260           pos = expr_pc;
8261           assign_component (container, lhs, ind, exp, &pos);
8262         }
8263     }
8264   ada_evaluate_subexp (NULL, exp, pos, EVAL_SKIP);
8265 }
8266
8267 /* Add the interval [LOW .. HIGH] to the sorted set of intervals 
8268    [ INDICES[0] .. INDICES[1] ],..., [ INDICES[*SIZE-2] .. INDICES[*SIZE-1] ],
8269    modifying *SIZE as needed.  It is an error if *SIZE exceeds
8270    MAX_SIZE.  The resulting intervals do not overlap.  */
8271 static void
8272 add_component_interval (LONGEST low, LONGEST high, 
8273                         LONGEST* indices, int *size, int max_size)
8274 {
8275   int i, j;
8276   for (i = 0; i < *size; i += 2) {
8277     if (high >= indices[i] && low <= indices[i + 1])
8278       {
8279         int kh;
8280         for (kh = i + 2; kh < *size; kh += 2)
8281           if (high < indices[kh])
8282             break;
8283         if (low < indices[i])
8284           indices[i] = low;
8285         indices[i + 1] = indices[kh - 1];
8286         if (high > indices[i + 1])
8287           indices[i + 1] = high;
8288         memcpy (indices + i + 2, indices + kh, *size - kh);
8289         *size -= kh - i - 2;
8290         return;
8291       }
8292     else if (high < indices[i])
8293       break;
8294   }
8295         
8296   if (*size == max_size)
8297     error (_("Internal error: miscounted aggregate components."));
8298   *size += 2;
8299   for (j = *size-1; j >= i+2; j -= 1)
8300     indices[j] = indices[j - 2];
8301   indices[i] = low;
8302   indices[i + 1] = high;
8303 }
8304
8305 /* Perform and Ada cast of ARG2 to type TYPE if the type of ARG2
8306    is different.  */
8307
8308 static struct value *
8309 ada_value_cast (struct type *type, struct value *arg2, enum noside noside)
8310 {
8311   if (type == ada_check_typedef (value_type (arg2)))
8312     return arg2;
8313
8314   if (ada_is_fixed_point_type (type))
8315     return (cast_to_fixed (type, arg2));
8316
8317   if (ada_is_fixed_point_type (value_type (arg2)))
8318     return cast_from_fixed (type, arg2);
8319
8320   return value_cast (type, arg2);
8321 }
8322
8323 static struct value *
8324 ada_evaluate_subexp (struct type *expect_type, struct expression *exp,
8325                      int *pos, enum noside noside)
8326 {
8327   enum exp_opcode op;
8328   int tem, tem2, tem3;
8329   int pc;
8330   struct value *arg1 = NULL, *arg2 = NULL, *arg3;
8331   struct type *type;
8332   int nargs, oplen;
8333   struct value **argvec;
8334
8335   pc = *pos;
8336   *pos += 1;
8337   op = exp->elts[pc].opcode;
8338
8339   switch (op)
8340     {
8341     default:
8342       *pos -= 1;
8343       arg1 = evaluate_subexp_standard (expect_type, exp, pos, noside);
8344       arg1 = unwrap_value (arg1);
8345
8346       /* If evaluating an OP_DOUBLE and an EXPECT_TYPE was provided,
8347          then we need to perform the conversion manually, because
8348          evaluate_subexp_standard doesn't do it.  This conversion is
8349          necessary in Ada because the different kinds of float/fixed
8350          types in Ada have different representations.
8351
8352          Similarly, we need to perform the conversion from OP_LONG
8353          ourselves.  */
8354       if ((op == OP_DOUBLE || op == OP_LONG) && expect_type != NULL)
8355         arg1 = ada_value_cast (expect_type, arg1, noside);
8356
8357       return arg1;
8358
8359     case OP_STRING:
8360       {
8361         struct value *result;
8362         *pos -= 1;
8363         result = evaluate_subexp_standard (expect_type, exp, pos, noside);
8364         /* The result type will have code OP_STRING, bashed there from 
8365            OP_ARRAY.  Bash it back.  */
8366         if (TYPE_CODE (value_type (result)) == TYPE_CODE_STRING)
8367           TYPE_CODE (value_type (result)) = TYPE_CODE_ARRAY;
8368         return result;
8369       }
8370
8371     case UNOP_CAST:
8372       (*pos) += 2;
8373       type = exp->elts[pc + 1].type;
8374       arg1 = evaluate_subexp (type, exp, pos, noside);
8375       if (noside == EVAL_SKIP)
8376         goto nosideret;
8377       arg1 = ada_value_cast (type, arg1, noside);
8378       return arg1;
8379
8380     case UNOP_QUAL:
8381       (*pos) += 2;
8382       type = exp->elts[pc + 1].type;
8383       return ada_evaluate_subexp (type, exp, pos, noside);
8384
8385     case BINOP_ASSIGN:
8386       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8387       if (exp->elts[*pos].opcode == OP_AGGREGATE)
8388         {
8389           arg1 = assign_aggregate (arg1, arg1, exp, pos, noside);
8390           if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
8391             return arg1;
8392           return ada_value_assign (arg1, arg1);
8393         }
8394       /* Force the evaluation of the rhs ARG2 to the type of the lhs ARG1,
8395          except if the lhs of our assignment is a convenience variable.
8396          In the case of assigning to a convenience variable, the lhs
8397          should be exactly the result of the evaluation of the rhs.  */
8398       type = value_type (arg1);
8399       if (VALUE_LVAL (arg1) == lval_internalvar)
8400          type = NULL;
8401       arg2 = evaluate_subexp (type, exp, pos, noside);
8402       if (noside == EVAL_SKIP || noside == EVAL_AVOID_SIDE_EFFECTS)
8403         return arg1;
8404       if (ada_is_fixed_point_type (value_type (arg1)))
8405         arg2 = cast_to_fixed (value_type (arg1), arg2);
8406       else if (ada_is_fixed_point_type (value_type (arg2)))
8407         error
8408           (_("Fixed-point values must be assigned to fixed-point variables"));
8409       else
8410         arg2 = coerce_for_assign (value_type (arg1), arg2);
8411       return ada_value_assign (arg1, arg2);
8412
8413     case BINOP_ADD:
8414       arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
8415       arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
8416       if (noside == EVAL_SKIP)
8417         goto nosideret;
8418       if (TYPE_CODE (value_type (arg1)) == TYPE_CODE_PTR)
8419         return (value_from_longest
8420                  (value_type (arg1),
8421                   value_as_long (arg1) + value_as_long (arg2)));
8422       if ((ada_is_fixed_point_type (value_type (arg1))
8423            || ada_is_fixed_point_type (value_type (arg2)))
8424           && value_type (arg1) != value_type (arg2))
8425         error (_("Operands of fixed-point addition must have the same type"));
8426       /* Do the addition, and cast the result to the type of the first
8427          argument.  We cannot cast the result to a reference type, so if
8428          ARG1 is a reference type, find its underlying type.  */
8429       type = value_type (arg1);
8430       while (TYPE_CODE (type) == TYPE_CODE_REF)
8431         type = TYPE_TARGET_TYPE (type);
8432       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
8433       return value_cast (type, value_binop (arg1, arg2, BINOP_ADD));
8434
8435     case BINOP_SUB:
8436       arg1 = evaluate_subexp_with_coercion (exp, pos, noside);
8437       arg2 = evaluate_subexp_with_coercion (exp, pos, noside);
8438       if (noside == EVAL_SKIP)
8439         goto nosideret;
8440       if (TYPE_CODE (value_type (arg1)) == TYPE_CODE_PTR)
8441         return (value_from_longest
8442                  (value_type (arg1),
8443                   value_as_long (arg1) - value_as_long (arg2)));
8444       if ((ada_is_fixed_point_type (value_type (arg1))
8445            || ada_is_fixed_point_type (value_type (arg2)))
8446           && value_type (arg1) != value_type (arg2))
8447         error (_("Operands of fixed-point subtraction must have the same type"));
8448       /* Do the substraction, and cast the result to the type of the first
8449          argument.  We cannot cast the result to a reference type, so if
8450          ARG1 is a reference type, find its underlying type.  */
8451       type = value_type (arg1);
8452       while (TYPE_CODE (type) == TYPE_CODE_REF)
8453         type = TYPE_TARGET_TYPE (type);
8454       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
8455       return value_cast (type, value_binop (arg1, arg2, BINOP_SUB));
8456
8457     case BINOP_MUL:
8458     case BINOP_DIV:
8459     case BINOP_REM:
8460     case BINOP_MOD:
8461       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8462       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8463       if (noside == EVAL_SKIP)
8464         goto nosideret;
8465       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
8466         {
8467           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
8468           return value_zero (value_type (arg1), not_lval);
8469         }
8470       else
8471         {
8472           type = builtin_type (exp->gdbarch)->builtin_double;
8473           if (ada_is_fixed_point_type (value_type (arg1)))
8474             arg1 = cast_from_fixed (type, arg1);
8475           if (ada_is_fixed_point_type (value_type (arg2)))
8476             arg2 = cast_from_fixed (type, arg2);
8477           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
8478           return ada_value_binop (arg1, arg2, op);
8479         }
8480
8481     case BINOP_EQUAL:
8482     case BINOP_NOTEQUAL:
8483       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8484       arg2 = evaluate_subexp (value_type (arg1), exp, pos, noside);
8485       if (noside == EVAL_SKIP)
8486         goto nosideret;
8487       if (noside == EVAL_AVOID_SIDE_EFFECTS)
8488         tem = 0;
8489       else
8490         {
8491           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
8492           tem = ada_value_equal (arg1, arg2);
8493         }
8494       if (op == BINOP_NOTEQUAL)
8495         tem = !tem;
8496       type = language_bool_type (exp->language_defn, exp->gdbarch);
8497       return value_from_longest (type, (LONGEST) tem);
8498
8499     case UNOP_NEG:
8500       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8501       if (noside == EVAL_SKIP)
8502         goto nosideret;
8503       else if (ada_is_fixed_point_type (value_type (arg1)))
8504         return value_cast (value_type (arg1), value_neg (arg1));
8505       else
8506         {
8507           unop_promote (exp->language_defn, exp->gdbarch, &arg1);
8508           return value_neg (arg1);
8509         }
8510
8511     case BINOP_LOGICAL_AND:
8512     case BINOP_LOGICAL_OR:
8513     case UNOP_LOGICAL_NOT:
8514       {
8515         struct value *val;
8516
8517         *pos -= 1;
8518         val = evaluate_subexp_standard (expect_type, exp, pos, noside);
8519         type = language_bool_type (exp->language_defn, exp->gdbarch);
8520         return value_cast (type, val);
8521       }
8522
8523     case BINOP_BITWISE_AND:
8524     case BINOP_BITWISE_IOR:
8525     case BINOP_BITWISE_XOR:
8526       {
8527         struct value *val;
8528
8529         arg1 = evaluate_subexp (NULL_TYPE, exp, pos, EVAL_AVOID_SIDE_EFFECTS);
8530         *pos = pc;
8531         val = evaluate_subexp_standard (expect_type, exp, pos, noside);
8532
8533         return value_cast (value_type (arg1), val);
8534       }
8535
8536     case OP_VAR_VALUE:
8537       *pos -= 1;
8538
8539       if (noside == EVAL_SKIP)
8540         {
8541           *pos += 4;
8542           goto nosideret;
8543         }
8544       else if (SYMBOL_DOMAIN (exp->elts[pc + 2].symbol) == UNDEF_DOMAIN)
8545         /* Only encountered when an unresolved symbol occurs in a
8546            context other than a function call, in which case, it is
8547            invalid.  */
8548         error (_("Unexpected unresolved symbol, %s, during evaluation"),
8549                SYMBOL_PRINT_NAME (exp->elts[pc + 2].symbol));
8550       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
8551         {
8552           type = static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol));
8553           if (ada_is_tagged_type (type, 0))
8554           {
8555             /* Tagged types are a little special in the fact that the real
8556                type is dynamic and can only be determined by inspecting the
8557                object's tag.  This means that we need to get the object's
8558                value first (EVAL_NORMAL) and then extract the actual object
8559                type from its tag.
8560
8561                Note that we cannot skip the final step where we extract
8562                the object type from its tag, because the EVAL_NORMAL phase
8563                results in dynamic components being resolved into fixed ones.
8564                This can cause problems when trying to print the type
8565                description of tagged types whose parent has a dynamic size:
8566                We use the type name of the "_parent" component in order
8567                to print the name of the ancestor type in the type description.
8568                If that component had a dynamic size, the resolution into
8569                a fixed type would result in the loss of that type name,
8570                thus preventing us from printing the name of the ancestor
8571                type in the type description.  */
8572             struct type *actual_type;
8573
8574             arg1 = evaluate_subexp (NULL_TYPE, exp, pos, EVAL_NORMAL);
8575             actual_type = type_from_tag (ada_value_tag (arg1));
8576             if (actual_type == NULL)
8577               /* If, for some reason, we were unable to determine
8578                  the actual type from the tag, then use the static
8579                  approximation that we just computed as a fallback.
8580                  This can happen if the debugging information is
8581                  incomplete, for instance.  */
8582               actual_type = type;
8583
8584             return value_zero (actual_type, not_lval);
8585           }
8586
8587           *pos += 4;
8588           return value_zero
8589             (to_static_fixed_type
8590              (static_unwrap_type (SYMBOL_TYPE (exp->elts[pc + 2].symbol))),
8591              not_lval);
8592         }
8593       else
8594         {
8595           arg1 =
8596             unwrap_value (evaluate_subexp_standard
8597                           (expect_type, exp, pos, noside));
8598           return ada_to_fixed_value (arg1);
8599         }
8600
8601     case OP_FUNCALL:
8602       (*pos) += 2;
8603
8604       /* Allocate arg vector, including space for the function to be
8605          called in argvec[0] and a terminating NULL.  */
8606       nargs = longest_to_int (exp->elts[pc + 1].longconst);
8607       argvec =
8608         (struct value **) alloca (sizeof (struct value *) * (nargs + 2));
8609
8610       if (exp->elts[*pos].opcode == OP_VAR_VALUE
8611           && SYMBOL_DOMAIN (exp->elts[pc + 5].symbol) == UNDEF_DOMAIN)
8612         error (_("Unexpected unresolved symbol, %s, during evaluation"),
8613                SYMBOL_PRINT_NAME (exp->elts[pc + 5].symbol));
8614       else
8615         {
8616           for (tem = 0; tem <= nargs; tem += 1)
8617             argvec[tem] = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8618           argvec[tem] = 0;
8619
8620           if (noside == EVAL_SKIP)
8621             goto nosideret;
8622         }
8623
8624       if (ada_is_packed_array_type (desc_base_type (value_type (argvec[0]))))
8625         argvec[0] = ada_coerce_to_simple_array (argvec[0]);
8626       else if (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_REF
8627                || (TYPE_CODE (value_type (argvec[0])) == TYPE_CODE_ARRAY
8628                    && VALUE_LVAL (argvec[0]) == lval_memory))
8629         argvec[0] = value_addr (argvec[0]);
8630
8631       type = ada_check_typedef (value_type (argvec[0]));
8632       if (TYPE_CODE (type) == TYPE_CODE_PTR)
8633         {
8634           switch (TYPE_CODE (ada_check_typedef (TYPE_TARGET_TYPE (type))))
8635             {
8636             case TYPE_CODE_FUNC:
8637               type = ada_check_typedef (TYPE_TARGET_TYPE (type));
8638               break;
8639             case TYPE_CODE_ARRAY:
8640               break;
8641             case TYPE_CODE_STRUCT:
8642               if (noside != EVAL_AVOID_SIDE_EFFECTS)
8643                 argvec[0] = ada_value_ind (argvec[0]);
8644               type = ada_check_typedef (TYPE_TARGET_TYPE (type));
8645               break;
8646             default:
8647               error (_("cannot subscript or call something of type `%s'"),
8648                      ada_type_name (value_type (argvec[0])));
8649               break;
8650             }
8651         }
8652
8653       switch (TYPE_CODE (type))
8654         {
8655         case TYPE_CODE_FUNC:
8656           if (noside == EVAL_AVOID_SIDE_EFFECTS)
8657             return allocate_value (TYPE_TARGET_TYPE (type));
8658           return call_function_by_hand (argvec[0], nargs, argvec + 1);
8659         case TYPE_CODE_STRUCT:
8660           {
8661             int arity;
8662
8663             arity = ada_array_arity (type);
8664             type = ada_array_element_type (type, nargs);
8665             if (type == NULL)
8666               error (_("cannot subscript or call a record"));
8667             if (arity != nargs)
8668               error (_("wrong number of subscripts; expecting %d"), arity);
8669             if (noside == EVAL_AVOID_SIDE_EFFECTS)
8670               return value_zero (ada_aligned_type (type), lval_memory);
8671             return
8672               unwrap_value (ada_value_subscript
8673                             (argvec[0], nargs, argvec + 1));
8674           }
8675         case TYPE_CODE_ARRAY:
8676           if (noside == EVAL_AVOID_SIDE_EFFECTS)
8677             {
8678               type = ada_array_element_type (type, nargs);
8679               if (type == NULL)
8680                 error (_("element type of array unknown"));
8681               else
8682                 return value_zero (ada_aligned_type (type), lval_memory);
8683             }
8684           return
8685             unwrap_value (ada_value_subscript
8686                           (ada_coerce_to_simple_array (argvec[0]),
8687                            nargs, argvec + 1));
8688         case TYPE_CODE_PTR:     /* Pointer to array */
8689           type = to_fixed_array_type (TYPE_TARGET_TYPE (type), NULL, 1);
8690           if (noside == EVAL_AVOID_SIDE_EFFECTS)
8691             {
8692               type = ada_array_element_type (type, nargs);
8693               if (type == NULL)
8694                 error (_("element type of array unknown"));
8695               else
8696                 return value_zero (ada_aligned_type (type), lval_memory);
8697             }
8698           return
8699             unwrap_value (ada_value_ptr_subscript (argvec[0], type,
8700                                                    nargs, argvec + 1));
8701
8702         default:
8703           error (_("Attempt to index or call something other than an "
8704                    "array or function"));
8705         }
8706
8707     case TERNOP_SLICE:
8708       {
8709         struct value *array = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8710         struct value *low_bound_val =
8711           evaluate_subexp (NULL_TYPE, exp, pos, noside);
8712         struct value *high_bound_val =
8713           evaluate_subexp (NULL_TYPE, exp, pos, noside);
8714         LONGEST low_bound;
8715         LONGEST high_bound;
8716         low_bound_val = coerce_ref (low_bound_val);
8717         high_bound_val = coerce_ref (high_bound_val);
8718         low_bound = pos_atr (low_bound_val);
8719         high_bound = pos_atr (high_bound_val);
8720
8721         if (noside == EVAL_SKIP)
8722           goto nosideret;
8723
8724         /* If this is a reference to an aligner type, then remove all
8725            the aligners.  */
8726         if (TYPE_CODE (value_type (array)) == TYPE_CODE_REF
8727             && ada_is_aligner_type (TYPE_TARGET_TYPE (value_type (array))))
8728           TYPE_TARGET_TYPE (value_type (array)) =
8729             ada_aligned_type (TYPE_TARGET_TYPE (value_type (array)));
8730
8731         if (ada_is_packed_array_type (value_type (array)))
8732           error (_("cannot slice a packed array"));
8733
8734         /* If this is a reference to an array or an array lvalue,
8735            convert to a pointer.  */
8736         if (TYPE_CODE (value_type (array)) == TYPE_CODE_REF
8737             || (TYPE_CODE (value_type (array)) == TYPE_CODE_ARRAY
8738                 && VALUE_LVAL (array) == lval_memory))
8739           array = value_addr (array);
8740
8741         if (noside == EVAL_AVOID_SIDE_EFFECTS
8742             && ada_is_array_descriptor_type (ada_check_typedef
8743                                              (value_type (array))))
8744           return empty_array (ada_type_of_array (array, 0), low_bound);
8745
8746         array = ada_coerce_to_simple_array_ptr (array);
8747
8748         /* If we have more than one level of pointer indirection,
8749            dereference the value until we get only one level.  */
8750         while (TYPE_CODE (value_type (array)) == TYPE_CODE_PTR
8751                && (TYPE_CODE (TYPE_TARGET_TYPE (value_type (array)))
8752                      == TYPE_CODE_PTR))
8753           array = value_ind (array);
8754
8755         /* Make sure we really do have an array type before going further,
8756            to avoid a SEGV when trying to get the index type or the target
8757            type later down the road if the debug info generated by
8758            the compiler is incorrect or incomplete.  */
8759         if (!ada_is_simple_array_type (value_type (array)))
8760           error (_("cannot take slice of non-array"));
8761
8762         if (TYPE_CODE (value_type (array)) == TYPE_CODE_PTR)
8763           {
8764             if (high_bound < low_bound || noside == EVAL_AVOID_SIDE_EFFECTS)
8765               return empty_array (TYPE_TARGET_TYPE (value_type (array)),
8766                                   low_bound);
8767             else
8768               {
8769                 struct type *arr_type0 =
8770                   to_fixed_array_type (TYPE_TARGET_TYPE (value_type (array)),
8771                                        NULL, 1);
8772                 return ada_value_slice_from_ptr (array, arr_type0,
8773                                                  longest_to_int (low_bound),
8774                                                  longest_to_int (high_bound));
8775               }
8776           }
8777         else if (noside == EVAL_AVOID_SIDE_EFFECTS)
8778           return array;
8779         else if (high_bound < low_bound)
8780           return empty_array (value_type (array), low_bound);
8781         else
8782           return ada_value_slice (array, longest_to_int (low_bound),
8783                                   longest_to_int (high_bound));
8784       }
8785
8786     case UNOP_IN_RANGE:
8787       (*pos) += 2;
8788       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8789       type = exp->elts[pc + 1].type;
8790
8791       if (noside == EVAL_SKIP)
8792         goto nosideret;
8793
8794       switch (TYPE_CODE (type))
8795         {
8796         default:
8797           lim_warning (_("Membership test incompletely implemented; "
8798                          "always returns true"));
8799           type = language_bool_type (exp->language_defn, exp->gdbarch);
8800           return value_from_longest (type, (LONGEST) 1);
8801
8802         case TYPE_CODE_RANGE:
8803           arg2 = value_from_longest (type, TYPE_LOW_BOUND (type));
8804           arg3 = value_from_longest (type, TYPE_HIGH_BOUND (type));
8805           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
8806           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
8807           type = language_bool_type (exp->language_defn, exp->gdbarch);
8808           return
8809             value_from_longest (type,
8810                                 (value_less (arg1, arg3)
8811                                  || value_equal (arg1, arg3))
8812                                 && (value_less (arg2, arg1)
8813                                     || value_equal (arg2, arg1)));
8814         }
8815
8816     case BINOP_IN_BOUNDS:
8817       (*pos) += 2;
8818       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8819       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8820
8821       if (noside == EVAL_SKIP)
8822         goto nosideret;
8823
8824       if (noside == EVAL_AVOID_SIDE_EFFECTS)
8825         {
8826           type = language_bool_type (exp->language_defn, exp->gdbarch);
8827           return value_zero (type, not_lval);
8828         }
8829
8830       tem = longest_to_int (exp->elts[pc + 1].longconst);
8831
8832       if (tem < 1 || tem > ada_array_arity (value_type (arg2)))
8833         error (_("invalid dimension number to 'range"));
8834
8835       arg3 = ada_array_bound (arg2, tem, 1);
8836       arg2 = ada_array_bound (arg2, tem, 0);
8837
8838       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
8839       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
8840       type = language_bool_type (exp->language_defn, exp->gdbarch);
8841       return
8842         value_from_longest (type,
8843                             (value_less (arg1, arg3)
8844                              || value_equal (arg1, arg3))
8845                             && (value_less (arg2, arg1)
8846                                 || value_equal (arg2, arg1)));
8847
8848     case TERNOP_IN_RANGE:
8849       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8850       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8851       arg3 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8852
8853       if (noside == EVAL_SKIP)
8854         goto nosideret;
8855
8856       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
8857       binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg3);
8858       type = language_bool_type (exp->language_defn, exp->gdbarch);
8859       return
8860         value_from_longest (type,
8861                             (value_less (arg1, arg3)
8862                              || value_equal (arg1, arg3))
8863                             && (value_less (arg2, arg1)
8864                                 || value_equal (arg2, arg1)));
8865
8866     case OP_ATR_FIRST:
8867     case OP_ATR_LAST:
8868     case OP_ATR_LENGTH:
8869       {
8870         struct type *type_arg;
8871         if (exp->elts[*pos].opcode == OP_TYPE)
8872           {
8873             evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
8874             arg1 = NULL;
8875             type_arg = check_typedef (exp->elts[pc + 2].type);
8876           }
8877         else
8878           {
8879             arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8880             type_arg = NULL;
8881           }
8882
8883         if (exp->elts[*pos].opcode != OP_LONG)
8884           error (_("Invalid operand to '%s"), ada_attribute_name (op));
8885         tem = longest_to_int (exp->elts[*pos + 2].longconst);
8886         *pos += 4;
8887
8888         if (noside == EVAL_SKIP)
8889           goto nosideret;
8890
8891         if (type_arg == NULL)
8892           {
8893             arg1 = ada_coerce_ref (arg1);
8894
8895             if (ada_is_packed_array_type (value_type (arg1)))
8896               arg1 = ada_coerce_to_simple_array (arg1);
8897
8898             if (tem < 1 || tem > ada_array_arity (value_type (arg1)))
8899               error (_("invalid dimension number to '%s"),
8900                      ada_attribute_name (op));
8901
8902             if (noside == EVAL_AVOID_SIDE_EFFECTS)
8903               {
8904                 type = ada_index_type (value_type (arg1), tem);
8905                 if (type == NULL)
8906                   error
8907                     (_("attempt to take bound of something that is not an array"));
8908                 return allocate_value (type);
8909               }
8910
8911             switch (op)
8912               {
8913               default:          /* Should never happen.  */
8914                 error (_("unexpected attribute encountered"));
8915               case OP_ATR_FIRST:
8916                 return ada_array_bound (arg1, tem, 0);
8917               case OP_ATR_LAST:
8918                 return ada_array_bound (arg1, tem, 1);
8919               case OP_ATR_LENGTH:
8920                 return ada_array_length (arg1, tem);
8921               }
8922           }
8923         else if (discrete_type_p (type_arg))
8924           {
8925             struct type *range_type;
8926             char *name = ada_type_name (type_arg);
8927             range_type = NULL;
8928             if (name != NULL && TYPE_CODE (type_arg) != TYPE_CODE_ENUM)
8929               range_type =
8930                 to_fixed_range_type (name, NULL, TYPE_OBJFILE (type_arg));
8931             if (range_type == NULL)
8932               range_type = type_arg;
8933             switch (op)
8934               {
8935               default:
8936                 error (_("unexpected attribute encountered"));
8937               case OP_ATR_FIRST:
8938                 return value_from_longest 
8939                   (range_type, discrete_type_low_bound (range_type));
8940               case OP_ATR_LAST:
8941                 return value_from_longest
8942                   (range_type, discrete_type_high_bound (range_type));
8943               case OP_ATR_LENGTH:
8944                 error (_("the 'length attribute applies only to array types"));
8945               }
8946           }
8947         else if (TYPE_CODE (type_arg) == TYPE_CODE_FLT)
8948           error (_("unimplemented type attribute"));
8949         else
8950           {
8951             LONGEST low, high;
8952
8953             if (ada_is_packed_array_type (type_arg))
8954               type_arg = decode_packed_array_type (type_arg);
8955
8956             if (tem < 1 || tem > ada_array_arity (type_arg))
8957               error (_("invalid dimension number to '%s"),
8958                      ada_attribute_name (op));
8959
8960             type = ada_index_type (type_arg, tem);
8961             if (type == NULL)
8962               error
8963                 (_("attempt to take bound of something that is not an array"));
8964             if (noside == EVAL_AVOID_SIDE_EFFECTS)
8965               return allocate_value (type);
8966
8967             switch (op)
8968               {
8969               default:
8970                 error (_("unexpected attribute encountered"));
8971               case OP_ATR_FIRST:
8972                 low = ada_array_bound_from_type (type_arg, tem, 0, &type);
8973                 return value_from_longest (type, low);
8974               case OP_ATR_LAST:
8975                 high = ada_array_bound_from_type (type_arg, tem, 1, &type);
8976                 return value_from_longest (type, high);
8977               case OP_ATR_LENGTH:
8978                 low = ada_array_bound_from_type (type_arg, tem, 0, &type);
8979                 high = ada_array_bound_from_type (type_arg, tem, 1, NULL);
8980                 return value_from_longest (type, high - low + 1);
8981               }
8982           }
8983       }
8984
8985     case OP_ATR_TAG:
8986       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8987       if (noside == EVAL_SKIP)
8988         goto nosideret;
8989
8990       if (noside == EVAL_AVOID_SIDE_EFFECTS)
8991         return value_zero (ada_tag_type (arg1), not_lval);
8992
8993       return ada_value_tag (arg1);
8994
8995     case OP_ATR_MIN:
8996     case OP_ATR_MAX:
8997       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
8998       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
8999       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9000       if (noside == EVAL_SKIP)
9001         goto nosideret;
9002       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9003         return value_zero (value_type (arg1), not_lval);
9004       else
9005         {
9006           binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9007           return value_binop (arg1, arg2,
9008                               op == OP_ATR_MIN ? BINOP_MIN : BINOP_MAX);
9009         }
9010
9011     case OP_ATR_MODULUS:
9012       {
9013         struct type *type_arg = exp->elts[pc + 2].type;
9014         evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
9015
9016         if (noside == EVAL_SKIP)
9017           goto nosideret;
9018
9019         if (!ada_is_modular_type (type_arg))
9020           error (_("'modulus must be applied to modular type"));
9021
9022         return value_from_longest (TYPE_TARGET_TYPE (type_arg),
9023                                    ada_modulus (type_arg));
9024       }
9025
9026
9027     case OP_ATR_POS:
9028       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
9029       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9030       if (noside == EVAL_SKIP)
9031         goto nosideret;
9032       type = builtin_type (exp->gdbarch)->builtin_int;
9033       if (noside == EVAL_AVOID_SIDE_EFFECTS)
9034         return value_zero (type, not_lval);
9035       else
9036         return value_pos_atr (type, arg1);
9037
9038     case OP_ATR_SIZE:
9039       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9040       type = value_type (arg1);
9041
9042       /* If the argument is a reference, then dereference its type, since
9043          the user is really asking for the size of the actual object,
9044          not the size of the pointer.  */
9045       if (TYPE_CODE (type) == TYPE_CODE_REF)
9046         type = TYPE_TARGET_TYPE (type);
9047
9048       if (noside == EVAL_SKIP)
9049         goto nosideret;
9050       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9051         return value_zero (builtin_type_int32, not_lval);
9052       else
9053         return value_from_longest (builtin_type_int32,
9054                                    TARGET_CHAR_BIT * TYPE_LENGTH (type));
9055
9056     case OP_ATR_VAL:
9057       evaluate_subexp (NULL_TYPE, exp, pos, EVAL_SKIP);
9058       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9059       type = exp->elts[pc + 2].type;
9060       if (noside == EVAL_SKIP)
9061         goto nosideret;
9062       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9063         return value_zero (type, not_lval);
9064       else
9065         return value_val_atr (type, arg1);
9066
9067     case BINOP_EXP:
9068       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9069       arg2 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9070       if (noside == EVAL_SKIP)
9071         goto nosideret;
9072       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9073         return value_zero (value_type (arg1), not_lval);
9074       else
9075         {
9076           /* For integer exponentiation operations,
9077              only promote the first argument.  */
9078           if (is_integral_type (value_type (arg2)))
9079             unop_promote (exp->language_defn, exp->gdbarch, &arg1);
9080           else
9081             binop_promote (exp->language_defn, exp->gdbarch, &arg1, &arg2);
9082
9083           return value_binop (arg1, arg2, op);
9084         }
9085
9086     case UNOP_PLUS:
9087       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9088       if (noside == EVAL_SKIP)
9089         goto nosideret;
9090       else
9091         return arg1;
9092
9093     case UNOP_ABS:
9094       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9095       if (noside == EVAL_SKIP)
9096         goto nosideret;
9097       unop_promote (exp->language_defn, exp->gdbarch, &arg1);
9098       if (value_less (arg1, value_zero (value_type (arg1), not_lval)))
9099         return value_neg (arg1);
9100       else
9101         return arg1;
9102
9103     case UNOP_IND:
9104       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9105       if (noside == EVAL_SKIP)
9106         goto nosideret;
9107       type = ada_check_typedef (value_type (arg1));
9108       if (noside == EVAL_AVOID_SIDE_EFFECTS)
9109         {
9110           if (ada_is_array_descriptor_type (type))
9111             /* GDB allows dereferencing GNAT array descriptors.  */
9112             {
9113               struct type *arrType = ada_type_of_array (arg1, 0);
9114               if (arrType == NULL)
9115                 error (_("Attempt to dereference null array pointer."));
9116               return value_at_lazy (arrType, 0);
9117             }
9118           else if (TYPE_CODE (type) == TYPE_CODE_PTR
9119                    || TYPE_CODE (type) == TYPE_CODE_REF
9120                    /* In C you can dereference an array to get the 1st elt.  */
9121                    || TYPE_CODE (type) == TYPE_CODE_ARRAY)
9122             {
9123               type = to_static_fixed_type
9124                 (ada_aligned_type
9125                  (ada_check_typedef (TYPE_TARGET_TYPE (type))));
9126               check_size (type);
9127               return value_zero (type, lval_memory);
9128             }
9129           else if (TYPE_CODE (type) == TYPE_CODE_INT)
9130             {
9131               /* GDB allows dereferencing an int.  */
9132               if (expect_type == NULL)
9133                 return value_zero (builtin_type (exp->gdbarch)->builtin_int,
9134                                    lval_memory);
9135               else
9136                 {
9137                   expect_type = 
9138                     to_static_fixed_type (ada_aligned_type (expect_type));
9139                   return value_zero (expect_type, lval_memory);
9140                 }
9141             }
9142           else
9143             error (_("Attempt to take contents of a non-pointer value."));
9144         }
9145       arg1 = ada_coerce_ref (arg1);     /* FIXME: What is this for?? */
9146       type = ada_check_typedef (value_type (arg1));
9147
9148       if (TYPE_CODE (type) == TYPE_CODE_INT)
9149           /* GDB allows dereferencing an int.  If we were given
9150              the expect_type, then use that as the target type.
9151              Otherwise, assume that the target type is an int.  */
9152         {
9153           if (expect_type != NULL)
9154             return ada_value_ind (value_cast (lookup_pointer_type (expect_type),
9155                                               arg1));
9156           else
9157             return value_at_lazy (builtin_type (exp->gdbarch)->builtin_int,
9158                                   (CORE_ADDR) value_as_address (arg1));
9159         }
9160
9161       if (ada_is_array_descriptor_type (type))
9162         /* GDB allows dereferencing GNAT array descriptors.  */
9163         return ada_coerce_to_simple_array (arg1);
9164       else
9165         return ada_value_ind (arg1);
9166
9167     case STRUCTOP_STRUCT:
9168       tem = longest_to_int (exp->elts[pc + 1].longconst);
9169       (*pos) += 3 + BYTES_TO_EXP_ELEM (tem + 1);
9170       arg1 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
9171       if (noside == EVAL_SKIP)
9172         goto nosideret;
9173       if (noside == EVAL_AVOID_SIDE_EFFECTS)
9174         {
9175           struct type *type1 = value_type (arg1);
9176           if (ada_is_tagged_type (type1, 1))
9177             {
9178               type = ada_lookup_struct_elt_type (type1,
9179                                                  &exp->elts[pc + 2].string,
9180                                                  1, 1, NULL);
9181               if (type == NULL)
9182                 /* In this case, we assume that the field COULD exist
9183                    in some extension of the type.  Return an object of 
9184                    "type" void, which will match any formal 
9185                    (see ada_type_match). */
9186                 return value_zero (builtin_type_void, lval_memory);
9187             }
9188           else
9189             type =
9190               ada_lookup_struct_elt_type (type1, &exp->elts[pc + 2].string, 1,
9191                                           0, NULL);
9192
9193           return value_zero (ada_aligned_type (type), lval_memory);
9194         }
9195       else
9196         return
9197           ada_to_fixed_value (unwrap_value
9198                               (ada_value_struct_elt
9199                                (arg1, &exp->elts[pc + 2].string, 0)));
9200     case OP_TYPE:
9201       /* The value is not supposed to be used.  This is here to make it
9202          easier to accommodate expressions that contain types.  */
9203       (*pos) += 2;
9204       if (noside == EVAL_SKIP)
9205         goto nosideret;
9206       else if (noside == EVAL_AVOID_SIDE_EFFECTS)
9207         return allocate_value (exp->elts[pc + 1].type);
9208       else
9209         error (_("Attempt to use a type name as an expression"));
9210
9211     case OP_AGGREGATE:
9212     case OP_CHOICES:
9213     case OP_OTHERS:
9214     case OP_DISCRETE_RANGE:
9215     case OP_POSITIONAL:
9216     case OP_NAME:
9217       if (noside == EVAL_NORMAL)
9218         switch (op) 
9219           {
9220           case OP_NAME:
9221             error (_("Undefined name, ambiguous name, or renaming used in "
9222                      "component association: %s."), &exp->elts[pc+2].string);
9223           case OP_AGGREGATE:
9224             error (_("Aggregates only allowed on the right of an assignment"));
9225           default:
9226             internal_error (__FILE__, __LINE__, _("aggregate apparently mangled"));
9227           }
9228
9229       ada_forward_operator_length (exp, pc, &oplen, &nargs);
9230       *pos += oplen - 1;
9231       for (tem = 0; tem < nargs; tem += 1) 
9232         ada_evaluate_subexp (NULL, exp, pos, noside);
9233       goto nosideret;
9234     }
9235
9236 nosideret:
9237   return value_from_longest (builtin_type_int8, (LONGEST) 1);
9238 }
9239 \f
9240
9241                                 /* Fixed point */
9242
9243 /* If TYPE encodes an Ada fixed-point type, return the suffix of the
9244    type name that encodes the 'small and 'delta information.
9245    Otherwise, return NULL.  */
9246
9247 static const char *
9248 fixed_type_info (struct type *type)
9249 {
9250   const char *name = ada_type_name (type);
9251   enum type_code code = (type == NULL) ? TYPE_CODE_UNDEF : TYPE_CODE (type);
9252
9253   if ((code == TYPE_CODE_INT || code == TYPE_CODE_RANGE) && name != NULL)
9254     {
9255       const char *tail = strstr (name, "___XF_");
9256       if (tail == NULL)
9257         return NULL;
9258       else
9259         return tail + 5;
9260     }
9261   else if (code == TYPE_CODE_RANGE && TYPE_TARGET_TYPE (type) != type)
9262     return fixed_type_info (TYPE_TARGET_TYPE (type));
9263   else
9264     return NULL;
9265 }
9266
9267 /* Returns non-zero iff TYPE represents an Ada fixed-point type.  */
9268
9269 int
9270 ada_is_fixed_point_type (struct type *type)
9271 {
9272   return fixed_type_info (type) != NULL;
9273 }
9274
9275 /* Return non-zero iff TYPE represents a System.Address type.  */
9276
9277 int
9278 ada_is_system_address_type (struct type *type)
9279 {
9280   return (TYPE_NAME (type)
9281           && strcmp (TYPE_NAME (type), "system__address") == 0);
9282 }
9283
9284 /* Assuming that TYPE is the representation of an Ada fixed-point
9285    type, return its delta, or -1 if the type is malformed and the
9286    delta cannot be determined.  */
9287
9288 DOUBLEST
9289 ada_delta (struct type *type)
9290 {
9291   const char *encoding = fixed_type_info (type);
9292   DOUBLEST num, den;
9293
9294   /* Strictly speaking, num and den are encoded as integer.  However,
9295      they may not fit into a long, and they will have to be converted
9296      to DOUBLEST anyway.  So scan them as DOUBLEST.  */
9297   if (sscanf (encoding, "_%" DOUBLEST_SCAN_FORMAT "_%" DOUBLEST_SCAN_FORMAT,
9298               &num, &den) < 2)
9299     return -1.0;
9300   else
9301     return num / den;
9302 }
9303
9304 /* Assuming that ada_is_fixed_point_type (TYPE), return the scaling
9305    factor ('SMALL value) associated with the type.  */
9306
9307 static DOUBLEST
9308 scaling_factor (struct type *type)
9309 {
9310   const char *encoding = fixed_type_info (type);
9311   DOUBLEST num0, den0, num1, den1;
9312   int n;
9313
9314   /* Strictly speaking, num's and den's are encoded as integer.  However,
9315      they may not fit into a long, and they will have to be converted
9316      to DOUBLEST anyway.  So scan them as DOUBLEST.  */
9317   n = sscanf (encoding,
9318               "_%" DOUBLEST_SCAN_FORMAT "_%" DOUBLEST_SCAN_FORMAT
9319               "_%" DOUBLEST_SCAN_FORMAT "_%" DOUBLEST_SCAN_FORMAT,
9320               &num0, &den0, &num1, &den1);
9321
9322   if (n < 2)
9323     return 1.0;
9324   else if (n == 4)
9325     return num1 / den1;
9326   else
9327     return num0 / den0;
9328 }
9329
9330
9331 /* Assuming that X is the representation of a value of fixed-point
9332    type TYPE, return its floating-point equivalent.  */
9333
9334 DOUBLEST
9335 ada_fixed_to_float (struct type *type, LONGEST x)
9336 {
9337   return (DOUBLEST) x *scaling_factor (type);
9338 }
9339
9340 /* The representation of a fixed-point value of type TYPE
9341    corresponding to the value X.  */
9342
9343 LONGEST
9344 ada_float_to_fixed (struct type *type, DOUBLEST x)
9345 {
9346   return (LONGEST) (x / scaling_factor (type) + 0.5);
9347 }
9348
9349
9350                                 /* VAX floating formats */
9351
9352 /* Non-zero iff TYPE represents one of the special VAX floating-point
9353    types.  */
9354
9355 int
9356 ada_is_vax_floating_type (struct type *type)
9357 {
9358   int name_len =
9359     (ada_type_name (type) == NULL) ? 0 : strlen (ada_type_name (type));
9360   return
9361     name_len > 6
9362     && (TYPE_CODE (type) == TYPE_CODE_INT
9363         || TYPE_CODE (type) == TYPE_CODE_RANGE)
9364     && strncmp (ada_type_name (type) + name_len - 6, "___XF", 5) == 0;
9365 }
9366
9367 /* The type of special VAX floating-point type this is, assuming
9368    ada_is_vax_floating_point.  */
9369
9370 int
9371 ada_vax_float_type_suffix (struct type *type)
9372 {
9373   return ada_type_name (type)[strlen (ada_type_name (type)) - 1];
9374 }
9375
9376 /* A value representing the special debugging function that outputs
9377    VAX floating-point values of the type represented by TYPE.  Assumes
9378    ada_is_vax_floating_type (TYPE).  */
9379
9380 struct value *
9381 ada_vax_float_print_function (struct type *type)
9382 {
9383   switch (ada_vax_float_type_suffix (type))
9384     {
9385     case 'F':
9386       return get_var_value ("DEBUG_STRING_F", 0);
9387     case 'D':
9388       return get_var_value ("DEBUG_STRING_D", 0);
9389     case 'G':
9390       return get_var_value ("DEBUG_STRING_G", 0);
9391     default:
9392       error (_("invalid VAX floating-point type"));
9393     }
9394 }
9395 \f
9396
9397                                 /* Range types */
9398
9399 /* Scan STR beginning at position K for a discriminant name, and
9400    return the value of that discriminant field of DVAL in *PX.  If
9401    PNEW_K is not null, put the position of the character beyond the
9402    name scanned in *PNEW_K.  Return 1 if successful; return 0 and do
9403    not alter *PX and *PNEW_K if unsuccessful.  */
9404
9405 static int
9406 scan_discrim_bound (char *str, int k, struct value *dval, LONGEST * px,
9407                     int *pnew_k)
9408 {
9409   static char *bound_buffer = NULL;
9410   static size_t bound_buffer_len = 0;
9411   char *bound;
9412   char *pend;
9413   struct value *bound_val;
9414
9415   if (dval == NULL || str == NULL || str[k] == '\0')
9416     return 0;
9417
9418   pend = strstr (str + k, "__");
9419   if (pend == NULL)
9420     {
9421       bound = str + k;
9422       k += strlen (bound);
9423     }
9424   else
9425     {
9426       GROW_VECT (bound_buffer, bound_buffer_len, pend - (str + k) + 1);
9427       bound = bound_buffer;
9428       strncpy (bound_buffer, str + k, pend - (str + k));
9429       bound[pend - (str + k)] = '\0';
9430       k = pend - str;
9431     }
9432
9433   bound_val = ada_search_struct_field (bound, dval, 0, value_type (dval));
9434   if (bound_val == NULL)
9435     return 0;
9436
9437   *px = value_as_long (bound_val);
9438   if (pnew_k != NULL)
9439     *pnew_k = k;
9440   return 1;
9441 }
9442
9443 /* Value of variable named NAME in the current environment.  If
9444    no such variable found, then if ERR_MSG is null, returns 0, and
9445    otherwise causes an error with message ERR_MSG.  */
9446
9447 static struct value *
9448 get_var_value (char *name, char *err_msg)
9449 {
9450   struct ada_symbol_info *syms;
9451   int nsyms;
9452
9453   nsyms = ada_lookup_symbol_list (name, get_selected_block (0), VAR_DOMAIN,
9454                                   &syms);
9455
9456   if (nsyms != 1)
9457     {
9458       if (err_msg == NULL)
9459         return 0;
9460       else
9461         error (("%s"), err_msg);
9462     }
9463
9464   return value_of_variable (syms[0].sym, syms[0].block);
9465 }
9466
9467 /* Value of integer variable named NAME in the current environment.  If
9468    no such variable found, returns 0, and sets *FLAG to 0.  If
9469    successful, sets *FLAG to 1.  */
9470
9471 LONGEST
9472 get_int_var_value (char *name, int *flag)
9473 {
9474   struct value *var_val = get_var_value (name, 0);
9475
9476   if (var_val == 0)
9477     {
9478       if (flag != NULL)
9479         *flag = 0;
9480       return 0;
9481     }
9482   else
9483     {
9484       if (flag != NULL)
9485         *flag = 1;
9486       return value_as_long (var_val);
9487     }
9488 }
9489
9490
9491 /* Return a range type whose base type is that of the range type named
9492    NAME in the current environment, and whose bounds are calculated
9493    from NAME according to the GNAT range encoding conventions.
9494    Extract discriminant values, if needed, from DVAL.  If a new type
9495    must be created, allocate in OBJFILE's space.  The bounds
9496    information, in general, is encoded in NAME, the base type given in
9497    the named range type.  */
9498
9499 static struct type *
9500 to_fixed_range_type (char *name, struct value *dval, struct objfile *objfile)
9501 {
9502   struct type *raw_type = ada_find_any_type (name);
9503   struct type *base_type;
9504   char *subtype_info;
9505
9506   if (raw_type == NULL)
9507     base_type = builtin_type_int32;
9508   else if (TYPE_CODE (raw_type) == TYPE_CODE_RANGE)
9509     base_type = TYPE_TARGET_TYPE (raw_type);
9510   else
9511     base_type = raw_type;
9512
9513   subtype_info = strstr (name, "___XD");
9514   if (subtype_info == NULL)
9515     {
9516       LONGEST L = discrete_type_low_bound (raw_type);
9517       LONGEST U = discrete_type_high_bound (raw_type);
9518       if (L < INT_MIN || U > INT_MAX)
9519         return raw_type;
9520       else
9521         return create_range_type (alloc_type (objfile), raw_type, 
9522                                   discrete_type_low_bound (raw_type),
9523                                   discrete_type_high_bound (raw_type));
9524     }
9525   else
9526     {
9527       static char *name_buf = NULL;
9528       static size_t name_len = 0;
9529       int prefix_len = subtype_info - name;
9530       LONGEST L, U;
9531       struct type *type;
9532       char *bounds_str;
9533       int n;
9534
9535       GROW_VECT (name_buf, name_len, prefix_len + 5);
9536       strncpy (name_buf, name, prefix_len);
9537       name_buf[prefix_len] = '\0';
9538
9539       subtype_info += 5;
9540       bounds_str = strchr (subtype_info, '_');
9541       n = 1;
9542
9543       if (*subtype_info == 'L')
9544         {
9545           if (!ada_scan_number (bounds_str, n, &L, &n)
9546               && !scan_discrim_bound (bounds_str, n, dval, &L, &n))
9547             return raw_type;
9548           if (bounds_str[n] == '_')
9549             n += 2;
9550           else if (bounds_str[n] == '.')        /* FIXME? SGI Workshop kludge.  */
9551             n += 1;
9552           subtype_info += 1;
9553         }
9554       else
9555         {
9556           int ok;
9557           strcpy (name_buf + prefix_len, "___L");
9558           L = get_int_var_value (name_buf, &ok);
9559           if (!ok)
9560             {
9561               lim_warning (_("Unknown lower bound, using 1."));
9562               L = 1;
9563             }
9564         }
9565
9566       if (*subtype_info == 'U')
9567         {
9568           if (!ada_scan_number (bounds_str, n, &U, &n)
9569               && !scan_discrim_bound (bounds_str, n, dval, &U, &n))
9570             return raw_type;
9571         }
9572       else
9573         {
9574           int ok;
9575           strcpy (name_buf + prefix_len, "___U");
9576           U = get_int_var_value (name_buf, &ok);
9577           if (!ok)
9578             {
9579               lim_warning (_("Unknown upper bound, using %ld."), (long) L);
9580               U = L;
9581             }
9582         }
9583
9584       if (objfile == NULL)
9585         objfile = TYPE_OBJFILE (base_type);
9586       type = create_range_type (alloc_type (objfile), base_type, L, U);
9587       TYPE_NAME (type) = name;
9588       return type;
9589     }
9590 }
9591
9592 /* True iff NAME is the name of a range type.  */
9593
9594 int
9595 ada_is_range_type_name (const char *name)
9596 {
9597   return (name != NULL && strstr (name, "___XD"));
9598 }
9599 \f
9600
9601                                 /* Modular types */
9602
9603 /* True iff TYPE is an Ada modular type.  */
9604
9605 int
9606 ada_is_modular_type (struct type *type)
9607 {
9608   struct type *subranged_type = base_type (type);
9609
9610   return (subranged_type != NULL && TYPE_CODE (type) == TYPE_CODE_RANGE
9611           && TYPE_CODE (subranged_type) == TYPE_CODE_INT
9612           && TYPE_UNSIGNED (subranged_type));
9613 }
9614
9615 /* Try to determine the lower and upper bounds of the given modular type
9616    using the type name only.  Return non-zero and set L and U as the lower
9617    and upper bounds (respectively) if successful.  */
9618
9619 int
9620 ada_modulus_from_name (struct type *type, ULONGEST *modulus)
9621 {
9622   char *name = ada_type_name (type);
9623   char *suffix;
9624   int k;
9625   LONGEST U;
9626
9627   if (name == NULL)
9628     return 0;
9629
9630   /* Discrete type bounds are encoded using an __XD suffix.  In our case,
9631      we are looking for static bounds, which means an __XDLU suffix.
9632      Moreover, we know that the lower bound of modular types is always
9633      zero, so the actual suffix should start with "__XDLU_0__", and
9634      then be followed by the upper bound value.  */
9635   suffix = strstr (name, "__XDLU_0__");
9636   if (suffix == NULL)
9637     return 0;
9638   k = 10;
9639   if (!ada_scan_number (suffix, k, &U, NULL))
9640     return 0;
9641
9642   *modulus = (ULONGEST) U + 1;
9643   return 1;
9644 }
9645
9646 /* Assuming ada_is_modular_type (TYPE), the modulus of TYPE.  */
9647
9648 ULONGEST
9649 ada_modulus (struct type *type)
9650 {
9651   ULONGEST modulus;
9652
9653   /* Normally, the modulus of a modular type is equal to the value of
9654      its upper bound + 1.  However, the upper bound is currently stored
9655      as an int, which is not always big enough to hold the actual bound
9656      value.  To workaround this, try to take advantage of the encoding
9657      that GNAT uses with with discrete types.  To avoid some unnecessary
9658      parsing, we do this only when the size of TYPE is greater than
9659      the size of the field holding the bound.  */
9660   if (TYPE_LENGTH (type) > sizeof (TYPE_HIGH_BOUND (type))
9661       && ada_modulus_from_name (type, &modulus))
9662     return modulus;
9663
9664   return (ULONGEST) (unsigned int) TYPE_HIGH_BOUND (type) + 1;
9665 }
9666 \f
9667
9668 /* Ada exception catchpoint support:
9669    ---------------------------------
9670
9671    We support 3 kinds of exception catchpoints:
9672      . catchpoints on Ada exceptions
9673      . catchpoints on unhandled Ada exceptions
9674      . catchpoints on failed assertions
9675
9676    Exceptions raised during failed assertions, or unhandled exceptions
9677    could perfectly be caught with the general catchpoint on Ada exceptions.
9678    However, we can easily differentiate these two special cases, and having
9679    the option to distinguish these two cases from the rest can be useful
9680    to zero-in on certain situations.
9681
9682    Exception catchpoints are a specialized form of breakpoint,
9683    since they rely on inserting breakpoints inside known routines
9684    of the GNAT runtime.  The implementation therefore uses a standard
9685    breakpoint structure of the BP_BREAKPOINT type, but with its own set
9686    of breakpoint_ops.
9687
9688    Support in the runtime for exception catchpoints have been changed
9689    a few times already, and these changes affect the implementation
9690    of these catchpoints.  In order to be able to support several
9691    variants of the runtime, we use a sniffer that will determine
9692    the runtime variant used by the program being debugged.
9693
9694    At this time, we do not support the use of conditions on Ada exception
9695    catchpoints.  The COND and COND_STRING fields are therefore set
9696    to NULL (most of the time, see below).
9697    
9698    Conditions where EXP_STRING, COND, and COND_STRING are used:
9699
9700      When a user specifies the name of a specific exception in the case
9701      of catchpoints on Ada exceptions, we store the name of that exception
9702      in the EXP_STRING.  We then translate this request into an actual
9703      condition stored in COND_STRING, and then parse it into an expression
9704      stored in COND.  */
9705
9706 /* The different types of catchpoints that we introduced for catching
9707    Ada exceptions.  */
9708
9709 enum exception_catchpoint_kind
9710 {
9711   ex_catch_exception,
9712   ex_catch_exception_unhandled,
9713   ex_catch_assert
9714 };
9715
9716 /* Ada's standard exceptions.  */
9717
9718 static char *standard_exc[] = {
9719   "constraint_error",
9720   "program_error",
9721   "storage_error",
9722   "tasking_error"
9723 };
9724
9725 typedef CORE_ADDR (ada_unhandled_exception_name_addr_ftype) (void);
9726
9727 /* A structure that describes how to support exception catchpoints
9728    for a given executable.  */
9729
9730 struct exception_support_info
9731 {
9732    /* The name of the symbol to break on in order to insert
9733       a catchpoint on exceptions.  */
9734    const char *catch_exception_sym;
9735
9736    /* The name of the symbol to break on in order to insert
9737       a catchpoint on unhandled exceptions.  */
9738    const char *catch_exception_unhandled_sym;
9739
9740    /* The name of the symbol to break on in order to insert
9741       a catchpoint on failed assertions.  */
9742    const char *catch_assert_sym;
9743
9744    /* Assuming that the inferior just triggered an unhandled exception
9745       catchpoint, this function is responsible for returning the address
9746       in inferior memory where the name of that exception is stored.
9747       Return zero if the address could not be computed.  */
9748    ada_unhandled_exception_name_addr_ftype *unhandled_exception_name_addr;
9749 };
9750
9751 static CORE_ADDR ada_unhandled_exception_name_addr (void);
9752 static CORE_ADDR ada_unhandled_exception_name_addr_from_raise (void);
9753
9754 /* The following exception support info structure describes how to
9755    implement exception catchpoints with the latest version of the
9756    Ada runtime (as of 2007-03-06).  */
9757
9758 static const struct exception_support_info default_exception_support_info =
9759 {
9760   "__gnat_debug_raise_exception", /* catch_exception_sym */
9761   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
9762   "__gnat_debug_raise_assert_failure", /* catch_assert_sym */
9763   ada_unhandled_exception_name_addr
9764 };
9765
9766 /* The following exception support info structure describes how to
9767    implement exception catchpoints with a slightly older version
9768    of the Ada runtime.  */
9769
9770 static const struct exception_support_info exception_support_info_fallback =
9771 {
9772   "__gnat_raise_nodefer_with_msg", /* catch_exception_sym */
9773   "__gnat_unhandled_exception", /* catch_exception_unhandled_sym */
9774   "system__assertions__raise_assert_failure",  /* catch_assert_sym */
9775   ada_unhandled_exception_name_addr_from_raise
9776 };
9777
9778 /* For each executable, we sniff which exception info structure to use
9779    and cache it in the following global variable.  */
9780
9781 static const struct exception_support_info *exception_info = NULL;
9782
9783 /* Inspect the Ada runtime and determine which exception info structure
9784    should be used to provide support for exception catchpoints.
9785
9786    This function will always set exception_info, or raise an error.  */
9787
9788 static void
9789 ada_exception_support_info_sniffer (void)
9790 {
9791   struct symbol *sym;
9792
9793   /* If the exception info is already known, then no need to recompute it.  */
9794   if (exception_info != NULL)
9795     return;
9796
9797   /* Check the latest (default) exception support info.  */
9798   sym = standard_lookup (default_exception_support_info.catch_exception_sym,
9799                          NULL, VAR_DOMAIN);
9800   if (sym != NULL)
9801     {
9802       exception_info = &default_exception_support_info;
9803       return;
9804     }
9805
9806   /* Try our fallback exception suport info.  */
9807   sym = standard_lookup (exception_support_info_fallback.catch_exception_sym,
9808                          NULL, VAR_DOMAIN);
9809   if (sym != NULL)
9810     {
9811       exception_info = &exception_support_info_fallback;
9812       return;
9813     }
9814
9815   /* Sometimes, it is normal for us to not be able to find the routine
9816      we are looking for.  This happens when the program is linked with
9817      the shared version of the GNAT runtime, and the program has not been
9818      started yet.  Inform the user of these two possible causes if
9819      applicable.  */
9820
9821   if (ada_update_initial_language (language_unknown, NULL) != language_ada)
9822     error (_("Unable to insert catchpoint.  Is this an Ada main program?"));
9823
9824   /* If the symbol does not exist, then check that the program is
9825      already started, to make sure that shared libraries have been
9826      loaded.  If it is not started, this may mean that the symbol is
9827      in a shared library.  */
9828
9829   if (ptid_get_pid (inferior_ptid) == 0)
9830     error (_("Unable to insert catchpoint. Try to start the program first."));
9831
9832   /* At this point, we know that we are debugging an Ada program and
9833      that the inferior has been started, but we still are not able to
9834      find the run-time symbols. That can mean that we are in
9835      configurable run time mode, or that a-except as been optimized
9836      out by the linker...  In any case, at this point it is not worth
9837      supporting this feature.  */
9838
9839   error (_("Cannot insert catchpoints in this configuration."));
9840 }
9841
9842 /* An observer of "executable_changed" events.
9843    Its role is to clear certain cached values that need to be recomputed
9844    each time a new executable is loaded by GDB.  */
9845
9846 static void
9847 ada_executable_changed_observer (void)
9848 {
9849   /* If the executable changed, then it is possible that the Ada runtime
9850      is different.  So we need to invalidate the exception support info
9851      cache.  */
9852   exception_info = NULL;
9853 }
9854
9855 /* Return the name of the function at PC, NULL if could not find it.
9856    This function only checks the debugging information, not the symbol
9857    table.  */
9858
9859 static char *
9860 function_name_from_pc (CORE_ADDR pc)
9861 {
9862   char *func_name;
9863
9864   if (!find_pc_partial_function (pc, &func_name, NULL, NULL))
9865     return NULL;
9866
9867   return func_name;
9868 }
9869
9870 /* True iff FRAME is very likely to be that of a function that is
9871    part of the runtime system.  This is all very heuristic, but is
9872    intended to be used as advice as to what frames are uninteresting
9873    to most users.  */
9874
9875 static int
9876 is_known_support_routine (struct frame_info *frame)
9877 {
9878   struct symtab_and_line sal;
9879   char *func_name;
9880   int i;
9881
9882   /* If this code does not have any debugging information (no symtab),
9883      This cannot be any user code.  */
9884
9885   find_frame_sal (frame, &sal);
9886   if (sal.symtab == NULL)
9887     return 1;
9888
9889   /* If there is a symtab, but the associated source file cannot be
9890      located, then assume this is not user code:  Selecting a frame
9891      for which we cannot display the code would not be very helpful
9892      for the user.  This should also take care of case such as VxWorks
9893      where the kernel has some debugging info provided for a few units.  */
9894
9895   if (symtab_to_fullname (sal.symtab) == NULL)
9896     return 1;
9897
9898   /* Check the unit filename againt the Ada runtime file naming.
9899      We also check the name of the objfile against the name of some
9900      known system libraries that sometimes come with debugging info
9901      too.  */
9902
9903   for (i = 0; known_runtime_file_name_patterns[i] != NULL; i += 1)
9904     {
9905       re_comp (known_runtime_file_name_patterns[i]);
9906       if (re_exec (sal.symtab->filename))
9907         return 1;
9908       if (sal.symtab->objfile != NULL
9909           && re_exec (sal.symtab->objfile->name))
9910         return 1;
9911     }
9912
9913   /* Check whether the function is a GNAT-generated entity.  */
9914
9915   func_name = function_name_from_pc (get_frame_address_in_block (frame));
9916   if (func_name == NULL)
9917     return 1;
9918
9919   for (i = 0; known_auxiliary_function_name_patterns[i] != NULL; i += 1)
9920     {
9921       re_comp (known_auxiliary_function_name_patterns[i]);
9922       if (re_exec (func_name))
9923         return 1;
9924     }
9925
9926   return 0;
9927 }
9928
9929 /* Find the first frame that contains debugging information and that is not
9930    part of the Ada run-time, starting from FI and moving upward.  */
9931
9932 void
9933 ada_find_printable_frame (struct frame_info *fi)
9934 {
9935   for (; fi != NULL; fi = get_prev_frame (fi))
9936     {
9937       if (!is_known_support_routine (fi))
9938         {
9939           select_frame (fi);
9940           break;
9941         }
9942     }
9943
9944 }
9945
9946 /* Assuming that the inferior just triggered an unhandled exception
9947    catchpoint, return the address in inferior memory where the name
9948    of the exception is stored.
9949    
9950    Return zero if the address could not be computed.  */
9951
9952 static CORE_ADDR
9953 ada_unhandled_exception_name_addr (void)
9954 {
9955   return parse_and_eval_address ("e.full_name");
9956 }
9957
9958 /* Same as ada_unhandled_exception_name_addr, except that this function
9959    should be used when the inferior uses an older version of the runtime,
9960    where the exception name needs to be extracted from a specific frame
9961    several frames up in the callstack.  */
9962
9963 static CORE_ADDR
9964 ada_unhandled_exception_name_addr_from_raise (void)
9965 {
9966   int frame_level;
9967   struct frame_info *fi;
9968
9969   /* To determine the name of this exception, we need to select
9970      the frame corresponding to RAISE_SYM_NAME.  This frame is
9971      at least 3 levels up, so we simply skip the first 3 frames
9972      without checking the name of their associated function.  */
9973   fi = get_current_frame ();
9974   for (frame_level = 0; frame_level < 3; frame_level += 1)
9975     if (fi != NULL)
9976       fi = get_prev_frame (fi); 
9977
9978   while (fi != NULL)
9979     {
9980       const char *func_name =
9981         function_name_from_pc (get_frame_address_in_block (fi));
9982       if (func_name != NULL
9983           && strcmp (func_name, exception_info->catch_exception_sym) == 0)
9984         break; /* We found the frame we were looking for...  */
9985       fi = get_prev_frame (fi);
9986     }
9987
9988   if (fi == NULL)
9989     return 0;
9990
9991   select_frame (fi);
9992   return parse_and_eval_address ("id.full_name");
9993 }
9994
9995 /* Assuming the inferior just triggered an Ada exception catchpoint
9996    (of any type), return the address in inferior memory where the name
9997    of the exception is stored, if applicable.
9998
9999    Return zero if the address could not be computed, or if not relevant.  */
10000
10001 static CORE_ADDR
10002 ada_exception_name_addr_1 (enum exception_catchpoint_kind ex,
10003                            struct breakpoint *b)
10004 {
10005   switch (ex)
10006     {
10007       case ex_catch_exception:
10008         return (parse_and_eval_address ("e.full_name"));
10009         break;
10010
10011       case ex_catch_exception_unhandled:
10012         return exception_info->unhandled_exception_name_addr ();
10013         break;
10014       
10015       case ex_catch_assert:
10016         return 0;  /* Exception name is not relevant in this case.  */
10017         break;
10018
10019       default:
10020         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
10021         break;
10022     }
10023
10024   return 0; /* Should never be reached.  */
10025 }
10026
10027 /* Same as ada_exception_name_addr_1, except that it intercepts and contains
10028    any error that ada_exception_name_addr_1 might cause to be thrown.
10029    When an error is intercepted, a warning with the error message is printed,
10030    and zero is returned.  */
10031
10032 static CORE_ADDR
10033 ada_exception_name_addr (enum exception_catchpoint_kind ex,
10034                          struct breakpoint *b)
10035 {
10036   struct gdb_exception e;
10037   CORE_ADDR result = 0;
10038
10039   TRY_CATCH (e, RETURN_MASK_ERROR)
10040     {
10041       result = ada_exception_name_addr_1 (ex, b);
10042     }
10043
10044   if (e.reason < 0)
10045     {
10046       warning (_("failed to get exception name: %s"), e.message);
10047       return 0;
10048     }
10049
10050   return result;
10051 }
10052
10053 /* Implement the PRINT_IT method in the breakpoint_ops structure
10054    for all exception catchpoint kinds.  */
10055
10056 static enum print_stop_action
10057 print_it_exception (enum exception_catchpoint_kind ex, struct breakpoint *b)
10058 {
10059   const CORE_ADDR addr = ada_exception_name_addr (ex, b);
10060   char exception_name[256];
10061
10062   if (addr != 0)
10063     {
10064       read_memory (addr, exception_name, sizeof (exception_name) - 1);
10065       exception_name [sizeof (exception_name) - 1] = '\0';
10066     }
10067
10068   ada_find_printable_frame (get_current_frame ());
10069
10070   annotate_catchpoint (b->number);
10071   switch (ex)
10072     {
10073       case ex_catch_exception:
10074         if (addr != 0)
10075           printf_filtered (_("\nCatchpoint %d, %s at "),
10076                            b->number, exception_name);
10077         else
10078           printf_filtered (_("\nCatchpoint %d, exception at "), b->number);
10079         break;
10080       case ex_catch_exception_unhandled:
10081         if (addr != 0)
10082           printf_filtered (_("\nCatchpoint %d, unhandled %s at "),
10083                            b->number, exception_name);
10084         else
10085           printf_filtered (_("\nCatchpoint %d, unhandled exception at "),
10086                            b->number);
10087         break;
10088       case ex_catch_assert:
10089         printf_filtered (_("\nCatchpoint %d, failed assertion at "),
10090                          b->number);
10091         break;
10092     }
10093
10094   return PRINT_SRC_AND_LOC;
10095 }
10096
10097 /* Implement the PRINT_ONE method in the breakpoint_ops structure
10098    for all exception catchpoint kinds.  */
10099
10100 static void
10101 print_one_exception (enum exception_catchpoint_kind ex,
10102                      struct breakpoint *b, CORE_ADDR *last_addr)
10103
10104   struct value_print_options opts;
10105
10106   get_user_print_options (&opts);
10107   if (opts.addressprint)
10108     {
10109       annotate_field (4);
10110       ui_out_field_core_addr (uiout, "addr", b->loc->address);
10111     }
10112
10113   annotate_field (5);
10114   *last_addr = b->loc->address;
10115   switch (ex)
10116     {
10117       case ex_catch_exception:
10118         if (b->exp_string != NULL)
10119           {
10120             char *msg = xstrprintf (_("`%s' Ada exception"), b->exp_string);
10121             
10122             ui_out_field_string (uiout, "what", msg);
10123             xfree (msg);
10124           }
10125         else
10126           ui_out_field_string (uiout, "what", "all Ada exceptions");
10127         
10128         break;
10129
10130       case ex_catch_exception_unhandled:
10131         ui_out_field_string (uiout, "what", "unhandled Ada exceptions");
10132         break;
10133       
10134       case ex_catch_assert:
10135         ui_out_field_string (uiout, "what", "failed Ada assertions");
10136         break;
10137
10138       default:
10139         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
10140         break;
10141     }
10142 }
10143
10144 /* Implement the PRINT_MENTION method in the breakpoint_ops structure
10145    for all exception catchpoint kinds.  */
10146
10147 static void
10148 print_mention_exception (enum exception_catchpoint_kind ex,
10149                          struct breakpoint *b)
10150 {
10151   switch (ex)
10152     {
10153       case ex_catch_exception:
10154         if (b->exp_string != NULL)
10155           printf_filtered (_("Catchpoint %d: `%s' Ada exception"),
10156                            b->number, b->exp_string);
10157         else
10158           printf_filtered (_("Catchpoint %d: all Ada exceptions"), b->number);
10159         
10160         break;
10161
10162       case ex_catch_exception_unhandled:
10163         printf_filtered (_("Catchpoint %d: unhandled Ada exceptions"),
10164                          b->number);
10165         break;
10166       
10167       case ex_catch_assert:
10168         printf_filtered (_("Catchpoint %d: failed Ada assertions"), b->number);
10169         break;
10170
10171       default:
10172         internal_error (__FILE__, __LINE__, _("unexpected catchpoint type"));
10173         break;
10174     }
10175 }
10176
10177 /* Virtual table for "catch exception" breakpoints.  */
10178
10179 static enum print_stop_action
10180 print_it_catch_exception (struct breakpoint *b)
10181 {
10182   return print_it_exception (ex_catch_exception, b);
10183 }
10184
10185 static void
10186 print_one_catch_exception (struct breakpoint *b, CORE_ADDR *last_addr)
10187 {
10188   print_one_exception (ex_catch_exception, b, last_addr);
10189 }
10190
10191 static void
10192 print_mention_catch_exception (struct breakpoint *b)
10193 {
10194   print_mention_exception (ex_catch_exception, b);
10195 }
10196
10197 static struct breakpoint_ops catch_exception_breakpoint_ops =
10198 {
10199   NULL, /* insert */
10200   NULL, /* remove */
10201   NULL, /* breakpoint_hit */
10202   print_it_catch_exception,
10203   print_one_catch_exception,
10204   print_mention_catch_exception
10205 };
10206
10207 /* Virtual table for "catch exception unhandled" breakpoints.  */
10208
10209 static enum print_stop_action
10210 print_it_catch_exception_unhandled (struct breakpoint *b)
10211 {
10212   return print_it_exception (ex_catch_exception_unhandled, b);
10213 }
10214
10215 static void
10216 print_one_catch_exception_unhandled (struct breakpoint *b, CORE_ADDR *last_addr)
10217 {
10218   print_one_exception (ex_catch_exception_unhandled, b, last_addr);
10219 }
10220
10221 static void
10222 print_mention_catch_exception_unhandled (struct breakpoint *b)
10223 {
10224   print_mention_exception (ex_catch_exception_unhandled, b);
10225 }
10226
10227 static struct breakpoint_ops catch_exception_unhandled_breakpoint_ops = {
10228   NULL, /* insert */
10229   NULL, /* remove */
10230   NULL, /* breakpoint_hit */
10231   print_it_catch_exception_unhandled,
10232   print_one_catch_exception_unhandled,
10233   print_mention_catch_exception_unhandled
10234 };
10235
10236 /* Virtual table for "catch assert" breakpoints.  */
10237
10238 static enum print_stop_action
10239 print_it_catch_assert (struct breakpoint *b)
10240 {
10241   return print_it_exception (ex_catch_assert, b);
10242 }
10243
10244 static void
10245 print_one_catch_assert (struct breakpoint *b, CORE_ADDR *last_addr)
10246 {
10247   print_one_exception (ex_catch_assert, b, last_addr);
10248 }
10249
10250 static void
10251 print_mention_catch_assert (struct breakpoint *b)
10252 {
10253   print_mention_exception (ex_catch_assert, b);
10254 }
10255
10256 static struct breakpoint_ops catch_assert_breakpoint_ops = {
10257   NULL, /* insert */
10258   NULL, /* remove */
10259   NULL, /* breakpoint_hit */
10260   print_it_catch_assert,
10261   print_one_catch_assert,
10262   print_mention_catch_assert
10263 };
10264
10265 /* Return non-zero if B is an Ada exception catchpoint.  */
10266
10267 int
10268 ada_exception_catchpoint_p (struct breakpoint *b)
10269 {
10270   return (b->ops == &catch_exception_breakpoint_ops
10271           || b->ops == &catch_exception_unhandled_breakpoint_ops
10272           || b->ops == &catch_assert_breakpoint_ops);
10273 }
10274
10275 /* Return a newly allocated copy of the first space-separated token
10276    in ARGSP, and then adjust ARGSP to point immediately after that
10277    token.
10278
10279    Return NULL if ARGPS does not contain any more tokens.  */
10280
10281 static char *
10282 ada_get_next_arg (char **argsp)
10283 {
10284   char *args = *argsp;
10285   char *end;
10286   char *result;
10287
10288   /* Skip any leading white space.  */
10289
10290   while (isspace (*args))
10291     args++;
10292
10293   if (args[0] == '\0')
10294     return NULL; /* No more arguments.  */
10295   
10296   /* Find the end of the current argument.  */
10297
10298   end = args;
10299   while (*end != '\0' && !isspace (*end))
10300     end++;
10301
10302   /* Adjust ARGSP to point to the start of the next argument.  */
10303
10304   *argsp = end;
10305
10306   /* Make a copy of the current argument and return it.  */
10307
10308   result = xmalloc (end - args + 1);
10309   strncpy (result, args, end - args);
10310   result[end - args] = '\0';
10311   
10312   return result;
10313 }
10314
10315 /* Split the arguments specified in a "catch exception" command.  
10316    Set EX to the appropriate catchpoint type.
10317    Set EXP_STRING to the name of the specific exception if
10318    specified by the user.  */
10319
10320 static void
10321 catch_ada_exception_command_split (char *args,
10322                                    enum exception_catchpoint_kind *ex,
10323                                    char **exp_string)
10324 {
10325   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
10326   char *exception_name;
10327
10328   exception_name = ada_get_next_arg (&args);
10329   make_cleanup (xfree, exception_name);
10330
10331   /* Check that we do not have any more arguments.  Anything else
10332      is unexpected.  */
10333
10334   while (isspace (*args))
10335     args++;
10336
10337   if (args[0] != '\0')
10338     error (_("Junk at end of expression"));
10339
10340   discard_cleanups (old_chain);
10341
10342   if (exception_name == NULL)
10343     {
10344       /* Catch all exceptions.  */
10345       *ex = ex_catch_exception;
10346       *exp_string = NULL;
10347     }
10348   else if (strcmp (exception_name, "unhandled") == 0)
10349     {
10350       /* Catch unhandled exceptions.  */
10351       *ex = ex_catch_exception_unhandled;
10352       *exp_string = NULL;
10353     }
10354   else
10355     {
10356       /* Catch a specific exception.  */
10357       *ex = ex_catch_exception;
10358       *exp_string = exception_name;
10359     }
10360 }
10361
10362 /* Return the name of the symbol on which we should break in order to
10363    implement a catchpoint of the EX kind.  */
10364
10365 static const char *
10366 ada_exception_sym_name (enum exception_catchpoint_kind ex)
10367 {
10368   gdb_assert (exception_info != NULL);
10369
10370   switch (ex)
10371     {
10372       case ex_catch_exception:
10373         return (exception_info->catch_exception_sym);
10374         break;
10375       case ex_catch_exception_unhandled:
10376         return (exception_info->catch_exception_unhandled_sym);
10377         break;
10378       case ex_catch_assert:
10379         return (exception_info->catch_assert_sym);
10380         break;
10381       default:
10382         internal_error (__FILE__, __LINE__,
10383                         _("unexpected catchpoint kind (%d)"), ex);
10384     }
10385 }
10386
10387 /* Return the breakpoint ops "virtual table" used for catchpoints
10388    of the EX kind.  */
10389
10390 static struct breakpoint_ops *
10391 ada_exception_breakpoint_ops (enum exception_catchpoint_kind ex)
10392 {
10393   switch (ex)
10394     {
10395       case ex_catch_exception:
10396         return (&catch_exception_breakpoint_ops);
10397         break;
10398       case ex_catch_exception_unhandled:
10399         return (&catch_exception_unhandled_breakpoint_ops);
10400         break;
10401       case ex_catch_assert:
10402         return (&catch_assert_breakpoint_ops);
10403         break;
10404       default:
10405         internal_error (__FILE__, __LINE__,
10406                         _("unexpected catchpoint kind (%d)"), ex);
10407     }
10408 }
10409
10410 /* Return the condition that will be used to match the current exception
10411    being raised with the exception that the user wants to catch.  This
10412    assumes that this condition is used when the inferior just triggered
10413    an exception catchpoint.
10414    
10415    The string returned is a newly allocated string that needs to be
10416    deallocated later.  */
10417
10418 static char *
10419 ada_exception_catchpoint_cond_string (const char *exp_string)
10420 {
10421   int i;
10422
10423   /* The standard exceptions are a special case. They are defined in
10424      runtime units that have been compiled without debugging info; if
10425      EXP_STRING is the not-fully-qualified name of a standard
10426      exception (e.g. "constraint_error") then, during the evaluation
10427      of the condition expression, the symbol lookup on this name would
10428      *not* return this standard exception. The catchpoint condition
10429      may then be set only on user-defined exceptions which have the
10430      same not-fully-qualified name (e.g. my_package.constraint_error).
10431
10432      To avoid this unexcepted behavior, these standard exceptions are
10433      systematically prefixed by "standard". This means that "catch
10434      exception constraint_error" is rewritten into "catch exception
10435      standard.constraint_error".
10436
10437      If an exception named contraint_error is defined in another package of
10438      the inferior program, then the only way to specify this exception as a
10439      breakpoint condition is to use its fully-qualified named:
10440      e.g. my_package.constraint_error.  */
10441
10442   for (i = 0; i < sizeof (standard_exc) / sizeof (char *); i++)
10443     {
10444       if (strcmp (standard_exc [i], exp_string) == 0)
10445         {
10446           return xstrprintf ("long_integer (e) = long_integer (&standard.%s)",
10447                              exp_string);
10448         }
10449     }
10450   return xstrprintf ("long_integer (e) = long_integer (&%s)", exp_string);
10451 }
10452
10453 /* Return the expression corresponding to COND_STRING evaluated at SAL.  */
10454
10455 static struct expression *
10456 ada_parse_catchpoint_condition (char *cond_string,
10457                                 struct symtab_and_line sal)
10458 {
10459   return (parse_exp_1 (&cond_string, block_for_pc (sal.pc), 0));
10460 }
10461
10462 /* Return the symtab_and_line that should be used to insert an exception
10463    catchpoint of the TYPE kind.
10464
10465    EX_STRING should contain the name of a specific exception
10466    that the catchpoint should catch, or NULL otherwise.
10467
10468    The idea behind all the remaining parameters is that their names match
10469    the name of certain fields in the breakpoint structure that are used to
10470    handle exception catchpoints.  This function returns the value to which
10471    these fields should be set, depending on the type of catchpoint we need
10472    to create.
10473    
10474    If COND and COND_STRING are both non-NULL, any value they might
10475    hold will be free'ed, and then replaced by newly allocated ones.
10476    These parameters are left untouched otherwise.  */
10477
10478 static struct symtab_and_line
10479 ada_exception_sal (enum exception_catchpoint_kind ex, char *exp_string,
10480                    char **addr_string, char **cond_string,
10481                    struct expression **cond, struct breakpoint_ops **ops)
10482 {
10483   const char *sym_name;
10484   struct symbol *sym;
10485   struct symtab_and_line sal;
10486
10487   /* First, find out which exception support info to use.  */
10488   ada_exception_support_info_sniffer ();
10489
10490   /* Then lookup the function on which we will break in order to catch
10491      the Ada exceptions requested by the user.  */
10492
10493   sym_name = ada_exception_sym_name (ex);
10494   sym = standard_lookup (sym_name, NULL, VAR_DOMAIN);
10495
10496   /* The symbol we're looking up is provided by a unit in the GNAT runtime
10497      that should be compiled with debugging information.  As a result, we
10498      expect to find that symbol in the symtabs.  If we don't find it, then
10499      the target most likely does not support Ada exceptions, or we cannot
10500      insert exception breakpoints yet, because the GNAT runtime hasn't been
10501      loaded yet.  */
10502
10503   /* brobecker/2006-12-26: It is conceivable that the runtime was compiled
10504      in such a way that no debugging information is produced for the symbol
10505      we are looking for.  In this case, we could search the minimal symbols
10506      as a fall-back mechanism.  This would still be operating in degraded
10507      mode, however, as we would still be missing the debugging information
10508      that is needed in order to extract the name of the exception being
10509      raised (this name is printed in the catchpoint message, and is also
10510      used when trying to catch a specific exception).  We do not handle
10511      this case for now.  */
10512
10513   if (sym == NULL)
10514     error (_("Unable to break on '%s' in this configuration."), sym_name);
10515
10516   /* Make sure that the symbol we found corresponds to a function.  */
10517   if (SYMBOL_CLASS (sym) != LOC_BLOCK)
10518     error (_("Symbol \"%s\" is not a function (class = %d)"),
10519            sym_name, SYMBOL_CLASS (sym));
10520
10521   sal = find_function_start_sal (sym, 1);
10522
10523   /* Set ADDR_STRING.  */
10524
10525   *addr_string = xstrdup (sym_name);
10526
10527   /* Set the COND and COND_STRING (if not NULL).  */
10528
10529   if (cond_string != NULL && cond != NULL)
10530     {
10531       if (*cond_string != NULL)
10532         {
10533           xfree (*cond_string);
10534           *cond_string = NULL;
10535         }
10536       if (*cond != NULL)
10537         {
10538           xfree (*cond);
10539           *cond = NULL;
10540         }
10541       if (exp_string != NULL)
10542         {
10543           *cond_string = ada_exception_catchpoint_cond_string (exp_string);
10544           *cond = ada_parse_catchpoint_condition (*cond_string, sal);
10545         }
10546     }
10547
10548   /* Set OPS.  */
10549   *ops = ada_exception_breakpoint_ops (ex);
10550
10551   return sal;
10552 }
10553
10554 /* Parse the arguments (ARGS) of the "catch exception" command.
10555  
10556    Set TYPE to the appropriate exception catchpoint type.
10557    If the user asked the catchpoint to catch only a specific
10558    exception, then save the exception name in ADDR_STRING.
10559
10560    See ada_exception_sal for a description of all the remaining
10561    function arguments of this function.  */
10562
10563 struct symtab_and_line
10564 ada_decode_exception_location (char *args, char **addr_string,
10565                                char **exp_string, char **cond_string,
10566                                struct expression **cond,
10567                                struct breakpoint_ops **ops)
10568 {
10569   enum exception_catchpoint_kind ex;
10570
10571   catch_ada_exception_command_split (args, &ex, exp_string);
10572   return ada_exception_sal (ex, *exp_string, addr_string, cond_string,
10573                             cond, ops);
10574 }
10575
10576 struct symtab_and_line
10577 ada_decode_assert_location (char *args, char **addr_string,
10578                             struct breakpoint_ops **ops)
10579 {
10580   /* Check that no argument where provided at the end of the command.  */
10581
10582   if (args != NULL)
10583     {
10584       while (isspace (*args))
10585         args++;
10586       if (*args != '\0')
10587         error (_("Junk at end of arguments."));
10588     }
10589
10590   return ada_exception_sal (ex_catch_assert, NULL, addr_string, NULL, NULL,
10591                             ops);
10592 }
10593
10594                                 /* Operators */
10595 /* Information about operators given special treatment in functions
10596    below.  */
10597 /* Format: OP_DEFN (<operator>, <operator length>, <# args>, <binop>).  */
10598
10599 #define ADA_OPERATORS \
10600     OP_DEFN (OP_VAR_VALUE, 4, 0, 0) \
10601     OP_DEFN (BINOP_IN_BOUNDS, 3, 2, 0) \
10602     OP_DEFN (TERNOP_IN_RANGE, 1, 3, 0) \
10603     OP_DEFN (OP_ATR_FIRST, 1, 2, 0) \
10604     OP_DEFN (OP_ATR_LAST, 1, 2, 0) \
10605     OP_DEFN (OP_ATR_LENGTH, 1, 2, 0) \
10606     OP_DEFN (OP_ATR_IMAGE, 1, 2, 0) \
10607     OP_DEFN (OP_ATR_MAX, 1, 3, 0) \
10608     OP_DEFN (OP_ATR_MIN, 1, 3, 0) \
10609     OP_DEFN (OP_ATR_MODULUS, 1, 1, 0) \
10610     OP_DEFN (OP_ATR_POS, 1, 2, 0) \
10611     OP_DEFN (OP_ATR_SIZE, 1, 1, 0) \
10612     OP_DEFN (OP_ATR_TAG, 1, 1, 0) \
10613     OP_DEFN (OP_ATR_VAL, 1, 2, 0) \
10614     OP_DEFN (UNOP_QUAL, 3, 1, 0) \
10615     OP_DEFN (UNOP_IN_RANGE, 3, 1, 0) \
10616     OP_DEFN (OP_OTHERS, 1, 1, 0) \
10617     OP_DEFN (OP_POSITIONAL, 3, 1, 0) \
10618     OP_DEFN (OP_DISCRETE_RANGE, 1, 2, 0)
10619
10620 static void
10621 ada_operator_length (struct expression *exp, int pc, int *oplenp, int *argsp)
10622 {
10623   switch (exp->elts[pc - 1].opcode)
10624     {
10625     default:
10626       operator_length_standard (exp, pc, oplenp, argsp);
10627       break;
10628
10629 #define OP_DEFN(op, len, args, binop) \
10630     case op: *oplenp = len; *argsp = args; break;
10631       ADA_OPERATORS;
10632 #undef OP_DEFN
10633
10634     case OP_AGGREGATE:
10635       *oplenp = 3;
10636       *argsp = longest_to_int (exp->elts[pc - 2].longconst);
10637       break;
10638
10639     case OP_CHOICES:
10640       *oplenp = 3;
10641       *argsp = longest_to_int (exp->elts[pc - 2].longconst) + 1;
10642       break;
10643     }
10644 }
10645
10646 static char *
10647 ada_op_name (enum exp_opcode opcode)
10648 {
10649   switch (opcode)
10650     {
10651     default:
10652       return op_name_standard (opcode);
10653
10654 #define OP_DEFN(op, len, args, binop) case op: return #op;
10655       ADA_OPERATORS;
10656 #undef OP_DEFN
10657
10658     case OP_AGGREGATE:
10659       return "OP_AGGREGATE";
10660     case OP_CHOICES:
10661       return "OP_CHOICES";
10662     case OP_NAME:
10663       return "OP_NAME";
10664     }
10665 }
10666
10667 /* As for operator_length, but assumes PC is pointing at the first
10668    element of the operator, and gives meaningful results only for the 
10669    Ada-specific operators, returning 0 for *OPLENP and *ARGSP otherwise.  */
10670
10671 static void
10672 ada_forward_operator_length (struct expression *exp, int pc,
10673                              int *oplenp, int *argsp)
10674 {
10675   switch (exp->elts[pc].opcode)
10676     {
10677     default:
10678       *oplenp = *argsp = 0;
10679       break;
10680
10681 #define OP_DEFN(op, len, args, binop) \
10682     case op: *oplenp = len; *argsp = args; break;
10683       ADA_OPERATORS;
10684 #undef OP_DEFN
10685
10686     case OP_AGGREGATE:
10687       *oplenp = 3;
10688       *argsp = longest_to_int (exp->elts[pc + 1].longconst);
10689       break;
10690
10691     case OP_CHOICES:
10692       *oplenp = 3;
10693       *argsp = longest_to_int (exp->elts[pc + 1].longconst) + 1;
10694       break;
10695
10696     case OP_STRING:
10697     case OP_NAME:
10698       {
10699         int len = longest_to_int (exp->elts[pc + 1].longconst);
10700         *oplenp = 4 + BYTES_TO_EXP_ELEM (len + 1);
10701         *argsp = 0;
10702         break;
10703       }
10704     }
10705 }
10706
10707 static int
10708 ada_dump_subexp_body (struct expression *exp, struct ui_file *stream, int elt)
10709 {
10710   enum exp_opcode op = exp->elts[elt].opcode;
10711   int oplen, nargs;
10712   int pc = elt;
10713   int i;
10714
10715   ada_forward_operator_length (exp, elt, &oplen, &nargs);
10716
10717   switch (op)
10718     {
10719       /* Ada attributes ('Foo).  */
10720     case OP_ATR_FIRST:
10721     case OP_ATR_LAST:
10722     case OP_ATR_LENGTH:
10723     case OP_ATR_IMAGE:
10724     case OP_ATR_MAX:
10725     case OP_ATR_MIN:
10726     case OP_ATR_MODULUS:
10727     case OP_ATR_POS:
10728     case OP_ATR_SIZE:
10729     case OP_ATR_TAG:
10730     case OP_ATR_VAL:
10731       break;
10732
10733     case UNOP_IN_RANGE:
10734     case UNOP_QUAL:
10735       /* XXX: gdb_sprint_host_address, type_sprint */
10736       fprintf_filtered (stream, _("Type @"));
10737       gdb_print_host_address (exp->elts[pc + 1].type, stream);
10738       fprintf_filtered (stream, " (");
10739       type_print (exp->elts[pc + 1].type, NULL, stream, 0);
10740       fprintf_filtered (stream, ")");
10741       break;
10742     case BINOP_IN_BOUNDS:
10743       fprintf_filtered (stream, " (%d)",
10744                         longest_to_int (exp->elts[pc + 2].longconst));
10745       break;
10746     case TERNOP_IN_RANGE:
10747       break;
10748
10749     case OP_AGGREGATE:
10750     case OP_OTHERS:
10751     case OP_DISCRETE_RANGE:
10752     case OP_POSITIONAL:
10753     case OP_CHOICES:
10754       break;
10755
10756     case OP_NAME:
10757     case OP_STRING:
10758       {
10759         char *name = &exp->elts[elt + 2].string;
10760         int len = longest_to_int (exp->elts[elt + 1].longconst);
10761         fprintf_filtered (stream, "Text: `%.*s'", len, name);
10762         break;
10763       }
10764
10765     default:
10766       return dump_subexp_body_standard (exp, stream, elt);
10767     }
10768
10769   elt += oplen;
10770   for (i = 0; i < nargs; i += 1)
10771     elt = dump_subexp (exp, stream, elt);
10772
10773   return elt;
10774 }
10775
10776 /* The Ada extension of print_subexp (q.v.).  */
10777
10778 static void
10779 ada_print_subexp (struct expression *exp, int *pos,
10780                   struct ui_file *stream, enum precedence prec)
10781 {
10782   int oplen, nargs, i;
10783   int pc = *pos;
10784   enum exp_opcode op = exp->elts[pc].opcode;
10785
10786   ada_forward_operator_length (exp, pc, &oplen, &nargs);
10787
10788   *pos += oplen;
10789   switch (op)
10790     {
10791     default:
10792       *pos -= oplen;
10793       print_subexp_standard (exp, pos, stream, prec);
10794       return;
10795
10796     case OP_VAR_VALUE:
10797       fputs_filtered (SYMBOL_NATURAL_NAME (exp->elts[pc + 2].symbol), stream);
10798       return;
10799
10800     case BINOP_IN_BOUNDS:
10801       /* XXX: sprint_subexp */
10802       print_subexp (exp, pos, stream, PREC_SUFFIX);
10803       fputs_filtered (" in ", stream);
10804       print_subexp (exp, pos, stream, PREC_SUFFIX);
10805       fputs_filtered ("'range", stream);
10806       if (exp->elts[pc + 1].longconst > 1)
10807         fprintf_filtered (stream, "(%ld)",
10808                           (long) exp->elts[pc + 1].longconst);
10809       return;
10810
10811     case TERNOP_IN_RANGE:
10812       if (prec >= PREC_EQUAL)
10813         fputs_filtered ("(", stream);
10814       /* XXX: sprint_subexp */
10815       print_subexp (exp, pos, stream, PREC_SUFFIX);
10816       fputs_filtered (" in ", stream);
10817       print_subexp (exp, pos, stream, PREC_EQUAL);
10818       fputs_filtered (" .. ", stream);
10819       print_subexp (exp, pos, stream, PREC_EQUAL);
10820       if (prec >= PREC_EQUAL)
10821         fputs_filtered (")", stream);
10822       return;
10823
10824     case OP_ATR_FIRST:
10825     case OP_ATR_LAST:
10826     case OP_ATR_LENGTH:
10827     case OP_ATR_IMAGE:
10828     case OP_ATR_MAX:
10829     case OP_ATR_MIN:
10830     case OP_ATR_MODULUS:
10831     case OP_ATR_POS:
10832     case OP_ATR_SIZE:
10833     case OP_ATR_TAG:
10834     case OP_ATR_VAL:
10835       if (exp->elts[*pos].opcode == OP_TYPE)
10836         {
10837           if (TYPE_CODE (exp->elts[*pos + 1].type) != TYPE_CODE_VOID)
10838             LA_PRINT_TYPE (exp->elts[*pos + 1].type, "", stream, 0, 0);
10839           *pos += 3;
10840         }
10841       else
10842         print_subexp (exp, pos, stream, PREC_SUFFIX);
10843       fprintf_filtered (stream, "'%s", ada_attribute_name (op));
10844       if (nargs > 1)
10845         {
10846           int tem;
10847           for (tem = 1; tem < nargs; tem += 1)
10848             {
10849               fputs_filtered ((tem == 1) ? " (" : ", ", stream);
10850               print_subexp (exp, pos, stream, PREC_ABOVE_COMMA);
10851             }
10852           fputs_filtered (")", stream);
10853         }
10854       return;
10855
10856     case UNOP_QUAL:
10857       type_print (exp->elts[pc + 1].type, "", stream, 0);
10858       fputs_filtered ("'(", stream);
10859       print_subexp (exp, pos, stream, PREC_PREFIX);
10860       fputs_filtered (")", stream);
10861       return;
10862
10863     case UNOP_IN_RANGE:
10864       /* XXX: sprint_subexp */
10865       print_subexp (exp, pos, stream, PREC_SUFFIX);
10866       fputs_filtered (" in ", stream);
10867       LA_PRINT_TYPE (exp->elts[pc + 1].type, "", stream, 1, 0);
10868       return;
10869
10870     case OP_DISCRETE_RANGE:
10871       print_subexp (exp, pos, stream, PREC_SUFFIX);
10872       fputs_filtered ("..", stream);
10873       print_subexp (exp, pos, stream, PREC_SUFFIX);
10874       return;
10875
10876     case OP_OTHERS:
10877       fputs_filtered ("others => ", stream);
10878       print_subexp (exp, pos, stream, PREC_SUFFIX);
10879       return;
10880
10881     case OP_CHOICES:
10882       for (i = 0; i < nargs-1; i += 1)
10883         {
10884           if (i > 0)
10885             fputs_filtered ("|", stream);
10886           print_subexp (exp, pos, stream, PREC_SUFFIX);
10887         }
10888       fputs_filtered (" => ", stream);
10889       print_subexp (exp, pos, stream, PREC_SUFFIX);
10890       return;
10891       
10892     case OP_POSITIONAL:
10893       print_subexp (exp, pos, stream, PREC_SUFFIX);
10894       return;
10895
10896     case OP_AGGREGATE:
10897       fputs_filtered ("(", stream);
10898       for (i = 0; i < nargs; i += 1)
10899         {
10900           if (i > 0)
10901             fputs_filtered (", ", stream);
10902           print_subexp (exp, pos, stream, PREC_SUFFIX);
10903         }
10904       fputs_filtered (")", stream);
10905       return;
10906     }
10907 }
10908
10909 /* Table mapping opcodes into strings for printing operators
10910    and precedences of the operators.  */
10911
10912 static const struct op_print ada_op_print_tab[] = {
10913   {":=", BINOP_ASSIGN, PREC_ASSIGN, 1},
10914   {"or else", BINOP_LOGICAL_OR, PREC_LOGICAL_OR, 0},
10915   {"and then", BINOP_LOGICAL_AND, PREC_LOGICAL_AND, 0},
10916   {"or", BINOP_BITWISE_IOR, PREC_BITWISE_IOR, 0},
10917   {"xor", BINOP_BITWISE_XOR, PREC_BITWISE_XOR, 0},
10918   {"and", BINOP_BITWISE_AND, PREC_BITWISE_AND, 0},
10919   {"=", BINOP_EQUAL, PREC_EQUAL, 0},
10920   {"/=", BINOP_NOTEQUAL, PREC_EQUAL, 0},
10921   {"<=", BINOP_LEQ, PREC_ORDER, 0},
10922   {">=", BINOP_GEQ, PREC_ORDER, 0},
10923   {">", BINOP_GTR, PREC_ORDER, 0},
10924   {"<", BINOP_LESS, PREC_ORDER, 0},
10925   {">>", BINOP_RSH, PREC_SHIFT, 0},
10926   {"<<", BINOP_LSH, PREC_SHIFT, 0},
10927   {"+", BINOP_ADD, PREC_ADD, 0},
10928   {"-", BINOP_SUB, PREC_ADD, 0},
10929   {"&", BINOP_CONCAT, PREC_ADD, 0},
10930   {"*", BINOP_MUL, PREC_MUL, 0},
10931   {"/", BINOP_DIV, PREC_MUL, 0},
10932   {"rem", BINOP_REM, PREC_MUL, 0},
10933   {"mod", BINOP_MOD, PREC_MUL, 0},
10934   {"**", BINOP_EXP, PREC_REPEAT, 0},
10935   {"@", BINOP_REPEAT, PREC_REPEAT, 0},
10936   {"-", UNOP_NEG, PREC_PREFIX, 0},
10937   {"+", UNOP_PLUS, PREC_PREFIX, 0},
10938   {"not ", UNOP_LOGICAL_NOT, PREC_PREFIX, 0},
10939   {"not ", UNOP_COMPLEMENT, PREC_PREFIX, 0},
10940   {"abs ", UNOP_ABS, PREC_PREFIX, 0},
10941   {".all", UNOP_IND, PREC_SUFFIX, 1},
10942   {"'access", UNOP_ADDR, PREC_SUFFIX, 1},
10943   {"'size", OP_ATR_SIZE, PREC_SUFFIX, 1},
10944   {NULL, 0, 0, 0}
10945 };
10946 \f
10947 enum ada_primitive_types {
10948   ada_primitive_type_int,
10949   ada_primitive_type_long,
10950   ada_primitive_type_short,
10951   ada_primitive_type_char,
10952   ada_primitive_type_float,
10953   ada_primitive_type_double,
10954   ada_primitive_type_void,
10955   ada_primitive_type_long_long,
10956   ada_primitive_type_long_double,
10957   ada_primitive_type_natural,
10958   ada_primitive_type_positive,
10959   ada_primitive_type_system_address,
10960   nr_ada_primitive_types
10961 };
10962
10963 static void
10964 ada_language_arch_info (struct gdbarch *gdbarch,
10965                         struct language_arch_info *lai)
10966 {
10967   const struct builtin_type *builtin = builtin_type (gdbarch);
10968   lai->primitive_type_vector
10969     = GDBARCH_OBSTACK_CALLOC (gdbarch, nr_ada_primitive_types + 1,
10970                               struct type *);
10971   lai->primitive_type_vector [ada_primitive_type_int] =
10972     init_type (TYPE_CODE_INT,
10973                gdbarch_int_bit (gdbarch) / TARGET_CHAR_BIT,
10974                0, "integer", (struct objfile *) NULL);
10975   lai->primitive_type_vector [ada_primitive_type_long] =
10976     init_type (TYPE_CODE_INT,
10977                gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT,
10978                0, "long_integer", (struct objfile *) NULL);
10979   lai->primitive_type_vector [ada_primitive_type_short] =
10980     init_type (TYPE_CODE_INT,
10981                gdbarch_short_bit (gdbarch) / TARGET_CHAR_BIT,
10982                0, "short_integer", (struct objfile *) NULL);
10983   lai->string_char_type = 
10984     lai->primitive_type_vector [ada_primitive_type_char] =
10985     init_type (TYPE_CODE_INT, TARGET_CHAR_BIT / TARGET_CHAR_BIT,
10986                0, "character", (struct objfile *) NULL);
10987   lai->primitive_type_vector [ada_primitive_type_float] =
10988     init_type (TYPE_CODE_FLT,
10989                gdbarch_float_bit (gdbarch)/ TARGET_CHAR_BIT,
10990                0, "float", (struct objfile *) NULL);
10991   lai->primitive_type_vector [ada_primitive_type_double] =
10992     init_type (TYPE_CODE_FLT,
10993                gdbarch_double_bit (gdbarch) / TARGET_CHAR_BIT,
10994                0, "long_float", (struct objfile *) NULL);
10995   lai->primitive_type_vector [ada_primitive_type_long_long] =
10996     init_type (TYPE_CODE_INT, 
10997                gdbarch_long_long_bit (gdbarch) / TARGET_CHAR_BIT,
10998                0, "long_long_integer", (struct objfile *) NULL);
10999   lai->primitive_type_vector [ada_primitive_type_long_double] =
11000     init_type (TYPE_CODE_FLT,
11001                gdbarch_double_bit (gdbarch) / TARGET_CHAR_BIT,
11002                0, "long_long_float", (struct objfile *) NULL);
11003   lai->primitive_type_vector [ada_primitive_type_natural] =
11004     init_type (TYPE_CODE_INT,
11005                gdbarch_int_bit (gdbarch) / TARGET_CHAR_BIT,
11006                0, "natural", (struct objfile *) NULL);
11007   lai->primitive_type_vector [ada_primitive_type_positive] =
11008     init_type (TYPE_CODE_INT,
11009                gdbarch_int_bit (gdbarch) / TARGET_CHAR_BIT,
11010                0, "positive", (struct objfile *) NULL);
11011   lai->primitive_type_vector [ada_primitive_type_void] = builtin->builtin_void;
11012
11013   lai->primitive_type_vector [ada_primitive_type_system_address] =
11014     lookup_pointer_type (init_type (TYPE_CODE_VOID, 1, 0, "void",
11015                                     (struct objfile *) NULL));
11016   TYPE_NAME (lai->primitive_type_vector [ada_primitive_type_system_address])
11017     = "system__address";
11018
11019   lai->bool_type_symbol = NULL;
11020   lai->bool_type_default = builtin->builtin_bool;
11021 }
11022 \f
11023                                 /* Language vector */
11024
11025 /* Not really used, but needed in the ada_language_defn.  */
11026
11027 static void
11028 emit_char (int c, struct type *type, struct ui_file *stream, int quoter)
11029 {
11030   ada_emit_char (c, type, stream, quoter, 1);
11031 }
11032
11033 static int
11034 parse (void)
11035 {
11036   warnings_issued = 0;
11037   return ada_parse ();
11038 }
11039
11040 static const struct exp_descriptor ada_exp_descriptor = {
11041   ada_print_subexp,
11042   ada_operator_length,
11043   ada_op_name,
11044   ada_dump_subexp_body,
11045   ada_evaluate_subexp
11046 };
11047
11048 const struct language_defn ada_language_defn = {
11049   "ada",                        /* Language name */
11050   language_ada,
11051   range_check_off,
11052   type_check_off,
11053   case_sensitive_on,            /* Yes, Ada is case-insensitive, but
11054                                    that's not quite what this means.  */
11055   array_row_major,
11056   macro_expansion_no,
11057   &ada_exp_descriptor,
11058   parse,
11059   ada_error,
11060   resolve,
11061   ada_printchar,                /* Print a character constant */
11062   ada_printstr,                 /* Function to print string constant */
11063   emit_char,                    /* Function to print single char (not used) */
11064   ada_print_type,               /* Print a type using appropriate syntax */
11065   default_print_typedef,        /* Print a typedef using appropriate syntax */
11066   ada_val_print,                /* Print a value using appropriate syntax */
11067   ada_value_print,              /* Print a top-level value */
11068   NULL,                         /* Language specific skip_trampoline */
11069   NULL,                         /* name_of_this */
11070   ada_lookup_symbol_nonlocal,   /* Looking up non-local symbols.  */
11071   basic_lookup_transparent_type,        /* lookup_transparent_type */
11072   ada_la_decode,                /* Language specific symbol demangler */
11073   NULL,                         /* Language specific class_name_from_physname */
11074   ada_op_print_tab,             /* expression operators for printing */
11075   0,                            /* c-style arrays */
11076   1,                            /* String lower bound */
11077   ada_get_gdb_completer_word_break_characters,
11078   ada_make_symbol_completion_list,
11079   ada_language_arch_info,
11080   ada_print_array_index,
11081   default_pass_by_reference,
11082   c_get_string,
11083   LANG_MAGIC
11084 };
11085
11086 /* Provide a prototype to silence -Wmissing-prototypes.  */
11087 extern initialize_file_ftype _initialize_ada_language;
11088
11089 void
11090 _initialize_ada_language (void)
11091 {
11092   add_language (&ada_language_defn);
11093
11094   varsize_limit = 65536;
11095
11096   obstack_init (&symbol_list_obstack);
11097
11098   decoded_names_store = htab_create_alloc
11099     (256, htab_hash_string, (int (*)(const void *, const void *)) streq,
11100      NULL, xcalloc, xfree);
11101
11102   observer_attach_executable_changed (ada_executable_changed_observer);
11103 }