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