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