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