Automatic date update in version.in
[external/binutils.git] / gdb / rust-lang.c
1 /* Rust language support routines for GDB, the GNU debugger.
2
3    Copyright (C) 2016-2019 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21
22 #include <ctype.h>
23
24 #include "block.h"
25 #include "c-lang.h"
26 #include "charset.h"
27 #include "cp-support.h"
28 #include "demangle.h"
29 #include "gdbarch.h"
30 #include "infcall.h"
31 #include "objfiles.h"
32 #include "psymtab.h"
33 #include "rust-lang.h"
34 #include "typeprint.h"
35 #include "valprint.h"
36 #include "varobj.h"
37 #include <algorithm>
38 #include <string>
39 #include <vector>
40
41 /* See rust-lang.h.  */
42
43 const char *
44 rust_last_path_segment (const char *path)
45 {
46   const char *result = strrchr (path, ':');
47
48   if (result == NULL)
49     return path;
50   return result + 1;
51 }
52
53 /* See rust-lang.h.  */
54
55 std::string
56 rust_crate_for_block (const struct block *block)
57 {
58   const char *scope = block_scope (block);
59
60   if (scope[0] == '\0')
61     return std::string ();
62
63   return std::string (scope, cp_find_first_component (scope));
64 }
65
66 /* Return true if TYPE, which must be a struct type, represents a Rust
67    enum.  */
68
69 static bool
70 rust_enum_p (const struct type *type)
71 {
72   return (TYPE_CODE (type) == TYPE_CODE_STRUCT
73           && TYPE_NFIELDS (type) == 1
74           && TYPE_FLAG_DISCRIMINATED_UNION (TYPE_FIELD_TYPE (type, 0)));
75 }
76
77 /* Return true if TYPE, which must be an enum type, has no
78    variants.  */
79
80 static bool
81 rust_empty_enum_p (const struct type *type)
82 {
83   gdb_assert (rust_enum_p (type));
84   /* In Rust the enum always fills the containing structure.  */
85   gdb_assert (TYPE_FIELD_BITPOS (type, 0) == 0);
86
87   return TYPE_NFIELDS (TYPE_FIELD_TYPE (type, 0)) == 0;
88 }
89
90 /* Given an enum type and contents, find which variant is active.  */
91
92 static struct field *
93 rust_enum_variant (struct type *type, const gdb_byte *contents)
94 {
95   /* In Rust the enum always fills the containing structure.  */
96   gdb_assert (TYPE_FIELD_BITPOS (type, 0) == 0);
97
98   struct type *union_type = TYPE_FIELD_TYPE (type, 0);
99
100   int fieldno = value_union_variant (union_type, contents);
101   return &TYPE_FIELD (union_type, fieldno);
102 }
103
104 /* See rust-lang.h.  */
105
106 bool
107 rust_tuple_type_p (struct type *type)
108 {
109   /* The current implementation is a bit of a hack, but there's
110      nothing else in the debuginfo to distinguish a tuple from a
111      struct.  */
112   return (TYPE_CODE (type) == TYPE_CODE_STRUCT
113           && TYPE_NAME (type) != NULL
114           && TYPE_NAME (type)[0] == '(');
115 }
116
117 /* Return true if all non-static fields of a structlike type are in a
118    sequence like __0, __1, __2.  */
119
120 static bool
121 rust_underscore_fields (struct type *type)
122 {
123   int i, field_number;
124
125   field_number = 0;
126
127   if (TYPE_CODE (type) != TYPE_CODE_STRUCT)
128     return false;
129   for (i = 0; i < TYPE_NFIELDS (type); ++i)
130     {
131       if (!field_is_static (&TYPE_FIELD (type, i)))
132         {
133           char buf[20];
134
135           xsnprintf (buf, sizeof (buf), "__%d", field_number);
136           if (strcmp (buf, TYPE_FIELD_NAME (type, i)) != 0)
137             return false;
138           field_number++;
139         }
140     }
141   return true;
142 }
143
144 /* See rust-lang.h.  */
145
146 bool
147 rust_tuple_struct_type_p (struct type *type)
148 {
149   /* This is just an approximation until DWARF can represent Rust more
150      precisely.  We exclude zero-length structs because they may not
151      be tuple structs, and there's no way to tell.  */
152   return TYPE_NFIELDS (type) > 0 && rust_underscore_fields (type);
153 }
154
155 /* Return true if TYPE is a slice type, otherwise false.  */
156
157 static bool
158 rust_slice_type_p (struct type *type)
159 {
160   return (TYPE_CODE (type) == TYPE_CODE_STRUCT
161           && TYPE_NAME (type) != NULL
162           && (strncmp (TYPE_NAME (type), "&[", 2) == 0
163               || strcmp (TYPE_NAME (type), "&str") == 0));
164 }
165
166 /* Return true if TYPE is a range type, otherwise false.  */
167
168 static bool
169 rust_range_type_p (struct type *type)
170 {
171   int i;
172
173   if (TYPE_CODE (type) != TYPE_CODE_STRUCT
174       || TYPE_NFIELDS (type) > 2
175       || TYPE_NAME (type) == NULL
176       || strstr (TYPE_NAME (type), "::Range") == NULL)
177     return false;
178
179   if (TYPE_NFIELDS (type) == 0)
180     return true;
181
182   i = 0;
183   if (strcmp (TYPE_FIELD_NAME (type, 0), "start") == 0)
184     {
185       if (TYPE_NFIELDS (type) == 1)
186         return true;
187       i = 1;
188     }
189   else if (TYPE_NFIELDS (type) == 2)
190     {
191       /* First field had to be "start".  */
192       return false;
193     }
194
195   return strcmp (TYPE_FIELD_NAME (type, i), "end") == 0;
196 }
197
198 /* Return true if TYPE is an inclusive range type, otherwise false.
199    This is only valid for types which are already known to be range
200    types.  */
201
202 static bool
203 rust_inclusive_range_type_p (struct type *type)
204 {
205   return (strstr (TYPE_NAME (type), "::RangeInclusive") != NULL
206           || strstr (TYPE_NAME (type), "::RangeToInclusive") != NULL);
207 }
208
209 /* Return true if TYPE seems to be the type "u8", otherwise false.  */
210
211 static bool
212 rust_u8_type_p (struct type *type)
213 {
214   return (TYPE_CODE (type) == TYPE_CODE_INT
215           && TYPE_UNSIGNED (type)
216           && TYPE_LENGTH (type) == 1);
217 }
218
219 /* Return true if TYPE is a Rust character type.  */
220
221 static bool
222 rust_chartype_p (struct type *type)
223 {
224   return (TYPE_CODE (type) == TYPE_CODE_CHAR
225           && TYPE_LENGTH (type) == 4
226           && TYPE_UNSIGNED (type));
227 }
228
229 /* If VALUE represents a trait object pointer, return the underlying
230    pointer with the correct (i.e., runtime) type.  Otherwise, return
231    NULL.  */
232
233 static struct value *
234 rust_get_trait_object_pointer (struct value *value)
235 {
236   struct type *type = check_typedef (value_type (value));
237
238   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
239     return NULL;
240
241   /* Try to be a bit resilient if the ABI changes.  */
242   int vtable_field = 0;
243   for (int i = 0; i < 2; ++i)
244     {
245       if (strcmp (TYPE_FIELD_NAME (type, i), "vtable") == 0)
246         vtable_field = i;
247       else if (strcmp (TYPE_FIELD_NAME (type, i), "pointer") != 0)
248         return NULL;
249     }
250
251   CORE_ADDR vtable = value_as_address (value_field (value, vtable_field));
252   struct symbol *symbol = find_symbol_at_address (vtable);
253   if (symbol == NULL || symbol->subclass != SYMBOL_RUST_VTABLE)
254     return NULL;
255
256   struct rust_vtable_symbol *vtable_sym
257     = static_cast<struct rust_vtable_symbol *> (symbol);
258   struct type *pointer_type = lookup_pointer_type (vtable_sym->concrete_type);
259   return value_cast (pointer_type, value_field (value, 1 - vtable_field));
260 }
261
262 \f
263
264 /* la_emitchar implementation for Rust.  */
265
266 static void
267 rust_emitchar (int c, struct type *type, struct ui_file *stream, int quoter)
268 {
269   if (!rust_chartype_p (type))
270     generic_emit_char (c, type, stream, quoter,
271                        target_charset (get_type_arch (type)));
272   else if (c == '\\' || c == quoter)
273     fprintf_filtered (stream, "\\%c", c);
274   else if (c == '\n')
275     fputs_filtered ("\\n", stream);
276   else if (c == '\r')
277     fputs_filtered ("\\r", stream);
278   else if (c == '\t')
279     fputs_filtered ("\\t", stream);
280   else if (c == '\0')
281     fputs_filtered ("\\0", stream);
282   else if (c >= 32 && c <= 127 && isprint (c))
283     fputc_filtered (c, stream);
284   else if (c <= 255)
285     fprintf_filtered (stream, "\\x%02x", c);
286   else
287     fprintf_filtered (stream, "\\u{%06x}", c);
288 }
289
290 /* la_printchar implementation for Rust.  */
291
292 static void
293 rust_printchar (int c, struct type *type, struct ui_file *stream)
294 {
295   fputs_filtered ("'", stream);
296   LA_EMIT_CHAR (c, type, stream, '\'');
297   fputs_filtered ("'", stream);
298 }
299
300 /* la_printstr implementation for Rust.  */
301
302 static void
303 rust_printstr (struct ui_file *stream, struct type *type,
304                const gdb_byte *string, unsigned int length,
305                const char *user_encoding, int force_ellipses,
306                const struct value_print_options *options)
307 {
308   /* Rust always uses UTF-8, but let the caller override this if need
309      be.  */
310   const char *encoding = user_encoding;
311   if (user_encoding == NULL || !*user_encoding)
312     {
313       /* In Rust strings, characters are "u8".  */
314       if (rust_u8_type_p (type))
315         encoding = "UTF-8";
316       else
317         {
318           /* This is probably some C string, so let's let C deal with
319              it.  */
320           c_printstr (stream, type, string, length, user_encoding,
321                       force_ellipses, options);
322           return;
323         }
324     }
325
326   /* This is not ideal as it doesn't use our character printer.  */
327   generic_printstr (stream, type, string, length, encoding, force_ellipses,
328                     '"', 0, options);
329 }
330
331 \f
332
333 /* Helper function to print a string slice.  */
334
335 static void
336 rust_val_print_str (struct ui_file *stream, struct value *val,
337                     const struct value_print_options *options)
338 {
339   struct value *base = value_struct_elt (&val, NULL, "data_ptr", NULL,
340                                          "slice");
341   struct value *len = value_struct_elt (&val, NULL, "length", NULL, "slice");
342
343   val_print_string (TYPE_TARGET_TYPE (value_type (base)), "UTF-8",
344                     value_as_address (base), value_as_long (len), stream,
345                     options);
346 }
347
348 /* rust_val_print helper for structs and untagged unions.  */
349
350 static void
351 val_print_struct (struct type *type, int embedded_offset,
352                   CORE_ADDR address, struct ui_file *stream,
353                   int recurse, struct value *val,
354                   const struct value_print_options *options)
355 {
356   int i;
357   int first_field;
358
359   if (rust_slice_type_p (type) && strcmp (TYPE_NAME (type), "&str") == 0)
360     {
361       rust_val_print_str (stream, val, options);
362       return;
363     }
364
365   bool is_tuple = rust_tuple_type_p (type);
366   bool is_tuple_struct = !is_tuple && rust_tuple_struct_type_p (type);
367   struct value_print_options opts;
368
369   if (!is_tuple)
370     {
371       if (TYPE_NAME (type) != NULL)
372         fprintf_filtered (stream, "%s", TYPE_NAME (type));
373
374       if (TYPE_NFIELDS (type) == 0)
375         return;
376
377       if (TYPE_NAME (type) != NULL)
378         fputs_filtered (" ", stream);
379     }
380
381   if (is_tuple || is_tuple_struct)
382     fputs_filtered ("(", stream);
383   else
384     fputs_filtered ("{", stream);
385
386   opts = *options;
387   opts.deref_ref = 0;
388
389   first_field = 1;
390   for (i = 0; i < TYPE_NFIELDS (type); ++i)
391     {
392       if (field_is_static (&TYPE_FIELD (type, i)))
393         continue;
394
395       if (!first_field)
396         fputs_filtered (",", stream);
397
398       if (options->prettyformat)
399         {
400           fputs_filtered ("\n", stream);
401           print_spaces_filtered (2 + 2 * recurse, stream);
402         }
403       else if (!first_field)
404         fputs_filtered (" ", stream);
405
406       first_field = 0;
407
408       if (!is_tuple && !is_tuple_struct)
409         {
410           fputs_filtered (TYPE_FIELD_NAME (type, i), stream);
411           fputs_filtered (": ", stream);
412         }
413
414       val_print (TYPE_FIELD_TYPE (type, i),
415                  embedded_offset + TYPE_FIELD_BITPOS (type, i) / 8,
416                  address,
417                  stream, recurse + 1, val, &opts,
418                  current_language);
419     }
420
421   if (options->prettyformat)
422     {
423       fputs_filtered ("\n", stream);
424       print_spaces_filtered (2 * recurse, stream);
425     }
426
427   if (is_tuple || is_tuple_struct)
428     fputs_filtered (")", stream);
429   else
430     fputs_filtered ("}", stream);
431 }
432
433 /* rust_val_print helper for discriminated unions (Rust enums).  */
434
435 static void
436 rust_print_enum (struct type *type, int embedded_offset,
437                  CORE_ADDR address, struct ui_file *stream,
438                  int recurse, struct value *val,
439                  const struct value_print_options *options)
440 {
441   struct value_print_options opts = *options;
442
443   opts.deref_ref = 0;
444
445   if (rust_empty_enum_p (type))
446     {
447       /* Print the enum type name here to be more clear.  */
448       fprintf_filtered (stream, _("%s {<No data fields>}"), TYPE_NAME (type));
449       return;
450     }
451
452   const gdb_byte *valaddr = value_contents_for_printing (val);
453   struct field *variant_field = rust_enum_variant (type, valaddr);
454   embedded_offset += FIELD_BITPOS (*variant_field) / 8;
455   struct type *variant_type = FIELD_TYPE (*variant_field);
456
457   int nfields = TYPE_NFIELDS (variant_type);
458
459   bool is_tuple = rust_tuple_struct_type_p (variant_type);
460
461   fprintf_filtered (stream, "%s", TYPE_NAME (variant_type));
462   if (nfields == 0)
463     {
464       /* In case of a nullary variant like 'None', just output
465          the name. */
466       return;
467     }
468
469   /* In case of a non-nullary variant, we output 'Foo(x,y,z)'. */
470   if (is_tuple)
471     fprintf_filtered (stream, "(");
472   else
473     {
474       /* struct variant.  */
475       fprintf_filtered (stream, "{");
476     }
477
478   bool first_field = true;
479   for (int j = 0; j < TYPE_NFIELDS (variant_type); j++)
480     {
481       if (!first_field)
482         fputs_filtered (", ", stream);
483       first_field = false;
484
485       if (!is_tuple)
486         fprintf_filtered (stream, "%s: ",
487                           TYPE_FIELD_NAME (variant_type, j));
488
489       val_print (TYPE_FIELD_TYPE (variant_type, j),
490                  (embedded_offset
491                   + TYPE_FIELD_BITPOS (variant_type, j) / 8),
492                  address,
493                  stream, recurse + 1, val, &opts,
494                  current_language);
495     }
496
497   if (is_tuple)
498     fputs_filtered (")", stream);
499   else
500     fputs_filtered ("}", stream);
501 }
502
503 static const struct generic_val_print_decorations rust_decorations =
504 {
505   /* Complex isn't used in Rust, but we provide C-ish values just in
506      case.  */
507   "",
508   " + ",
509   " * I",
510   "true",
511   "false",
512   "()",
513   "[",
514   "]"
515 };
516
517 /* la_val_print implementation for Rust.  */
518
519 static void
520 rust_val_print (struct type *type, int embedded_offset,
521                 CORE_ADDR address, struct ui_file *stream, int recurse,
522                 struct value *val,
523                 const struct value_print_options *options)
524 {
525   const gdb_byte *valaddr = value_contents_for_printing (val);
526
527   type = check_typedef (type);
528   switch (TYPE_CODE (type))
529     {
530     case TYPE_CODE_PTR:
531       {
532         LONGEST low_bound, high_bound;
533         
534         if (TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_ARRAY
535             && rust_u8_type_p (TYPE_TARGET_TYPE (TYPE_TARGET_TYPE (type)))
536             && get_array_bounds (TYPE_TARGET_TYPE (type), &low_bound,
537                                  &high_bound)) {
538           /* We have a pointer to a byte string, so just print
539              that.  */
540           struct type *elttype = check_typedef (TYPE_TARGET_TYPE (type));
541           CORE_ADDR addr;
542           struct gdbarch *arch = get_type_arch (type);
543           int unit_size = gdbarch_addressable_memory_unit_size (arch);
544
545           addr = unpack_pointer (type, valaddr + embedded_offset * unit_size);
546           if (options->addressprint)
547             {
548               fputs_filtered (paddress (arch, addr), stream);
549               fputs_filtered (" ", stream);
550             }
551
552           fputs_filtered ("b", stream);
553           val_print_string (TYPE_TARGET_TYPE (elttype), "ASCII", addr,
554                             high_bound - low_bound + 1, stream,
555                             options);
556           break;
557         }
558       }
559       /* Fall through.  */
560
561     case TYPE_CODE_METHODPTR:
562     case TYPE_CODE_MEMBERPTR:
563       c_val_print (type, embedded_offset, address, stream,
564                    recurse, val, options);
565       break;
566
567     case TYPE_CODE_INT:
568       /* Recognize the unit type.  */
569       if (TYPE_UNSIGNED (type) && TYPE_LENGTH (type) == 0
570           && TYPE_NAME (type) != NULL && strcmp (TYPE_NAME (type), "()") == 0)
571         {
572           fputs_filtered ("()", stream);
573           break;
574         }
575       goto generic_print;
576
577     case TYPE_CODE_STRING:
578       {
579         struct gdbarch *arch = get_type_arch (type);
580         int unit_size = gdbarch_addressable_memory_unit_size (arch);
581         LONGEST low_bound, high_bound;
582
583         if (!get_array_bounds (type, &low_bound, &high_bound))
584           error (_("Could not determine the array bounds"));
585
586         /* If we see a plain TYPE_CODE_STRING, then we're printing a
587            byte string, hence the choice of "ASCII" as the
588            encoding.  */
589         fputs_filtered ("b", stream);
590         rust_printstr (stream, TYPE_TARGET_TYPE (type),
591                        valaddr + embedded_offset * unit_size,
592                        high_bound - low_bound + 1, "ASCII", 0, options);
593       }
594       break;
595
596     case TYPE_CODE_ARRAY:
597       {
598         LONGEST low_bound, high_bound;
599
600         if (get_array_bounds (type, &low_bound, &high_bound)
601             && high_bound - low_bound + 1 == 0)
602           fputs_filtered ("[]", stream);
603         else
604           goto generic_print;
605       }
606       break;
607
608     case TYPE_CODE_UNION:
609       /* Untagged unions are printed as if they are structs.  Since
610          the field bit positions overlap in the debuginfo, the code
611          for printing a union is same as that for a struct, the only
612          difference is that the input type will have overlapping
613          fields.  */
614       val_print_struct (type, embedded_offset, address, stream,
615                         recurse, val, options);
616       break;
617
618     case TYPE_CODE_STRUCT:
619       if (rust_enum_p (type))
620         rust_print_enum (type, embedded_offset, address, stream,
621                          recurse, val, options);
622       else
623         val_print_struct (type, embedded_offset, address, stream,
624                           recurse, val, options);
625       break;
626
627     default:
628     generic_print:
629       /* Nothing special yet.  */
630       generic_val_print (type, embedded_offset, address, stream,
631                          recurse, val, options, &rust_decorations);
632     }
633 }
634
635 \f
636
637 static void
638 rust_internal_print_type (struct type *type, const char *varstring,
639                           struct ui_file *stream, int show, int level,
640                           const struct type_print_options *flags,
641                           bool for_rust_enum, print_offset_data *podata);
642
643 /* Print a struct or union typedef.  */
644 static void
645 rust_print_struct_def (struct type *type, const char *varstring,
646                        struct ui_file *stream, int show, int level,
647                        const struct type_print_options *flags,
648                        bool for_rust_enum, print_offset_data *podata)
649 {
650   /* Print a tuple type simply.  */
651   if (rust_tuple_type_p (type))
652     {
653       fputs_filtered (TYPE_NAME (type), stream);
654       return;
655     }
656
657   /* If we see a base class, delegate to C.  */
658   if (TYPE_N_BASECLASSES (type) > 0)
659     c_print_type (type, varstring, stream, show, level, flags);
660
661   if (flags->print_offsets)
662     {
663       /* Temporarily bump the level so that the output lines up
664          correctly.  */
665       level += 2;
666     }
667
668   /* Compute properties of TYPE here because, in the enum case, the
669      rest of the code ends up looking only at the variant part.  */
670   const char *tagname = TYPE_NAME (type);
671   bool is_tuple_struct = rust_tuple_struct_type_p (type);
672   bool is_tuple = rust_tuple_type_p (type);
673   bool is_enum = rust_enum_p (type);
674
675   int enum_discriminant_index = -1;
676
677   if (for_rust_enum)
678     {
679       /* Already printing an outer enum, so nothing to print here.  */
680     }
681   else
682     {
683       /* This code path is also used by unions and enums.  */
684       if (is_enum)
685         {
686           fputs_filtered ("enum ", stream);
687
688           if (rust_empty_enum_p (type))
689             {
690               if (tagname != NULL)
691                 {
692                   fputs_filtered (tagname, stream);
693                   fputs_filtered (" ", stream);
694                 }
695               fputs_filtered ("{}", stream);
696               return;
697             }
698
699           type = TYPE_FIELD_TYPE (type, 0);
700
701           struct dynamic_prop *discriminant_prop
702             = get_dyn_prop (DYN_PROP_DISCRIMINATED, type);
703           struct discriminant_info *info
704             = (struct discriminant_info *) discriminant_prop->data.baton;
705           enum_discriminant_index = info->discriminant_index;
706         }
707       else if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
708         fputs_filtered ("struct ", stream);
709       else
710         fputs_filtered ("union ", stream);
711
712       if (tagname != NULL)
713         fputs_filtered (tagname, stream);
714     }
715
716   if (TYPE_NFIELDS (type) == 0 && !is_tuple)
717     return;
718   if (for_rust_enum && !flags->print_offsets)
719     fputs_filtered (is_tuple_struct ? "(" : "{", stream);
720   else
721     fputs_filtered (is_tuple_struct ? " (\n" : " {\n", stream);
722
723   /* When printing offsets, we rearrange the fields into storage
724      order.  This lets us show holes more clearly.  We work using
725      field indices here because it simplifies calls to
726      print_offset_data::update below.  */
727   std::vector<int> fields;
728   for (int i = 0; i < TYPE_NFIELDS (type); ++i)
729     {
730       if (field_is_static (&TYPE_FIELD (type, i)))
731         continue;
732       if (is_enum && i == enum_discriminant_index)
733         continue;
734       fields.push_back (i);
735     }
736   if (flags->print_offsets)
737     std::sort (fields.begin (), fields.end (),
738                [&] (int a, int b)
739                {
740                  return (TYPE_FIELD_BITPOS (type, a)
741                          < TYPE_FIELD_BITPOS (type, b));
742                });
743
744   for (int i : fields)
745     {
746       QUIT;
747
748       gdb_assert (!field_is_static (&TYPE_FIELD (type, i)));
749       gdb_assert (! (is_enum && i == enum_discriminant_index));
750
751       if (flags->print_offsets)
752         podata->update (type, i, stream);
753
754       /* We'd like to print "pub" here as needed, but rustc
755          doesn't emit the debuginfo, and our types don't have
756          cplus_struct_type attached.  */
757
758       /* For a tuple struct we print the type but nothing
759          else.  */
760       if (!for_rust_enum || flags->print_offsets)
761         print_spaces_filtered (level + 2, stream);
762       if (is_enum)
763         fputs_filtered (TYPE_FIELD_NAME (type, i), stream);
764       else if (!is_tuple_struct)
765         fprintf_filtered (stream, "%s: ", TYPE_FIELD_NAME (type, i));
766
767       rust_internal_print_type (TYPE_FIELD_TYPE (type, i), NULL,
768                                 stream, (is_enum ? show : show - 1),
769                                 level + 2, flags, is_enum, podata);
770       if (!for_rust_enum || flags->print_offsets)
771         fputs_filtered (",\n", stream);
772       /* Note that this check of "I" is ok because we only sorted the
773          fields by offset when print_offsets was set, so we won't take
774          this branch in that case.  */
775       else if (i + 1 < TYPE_NFIELDS (type))
776         fputs_filtered (", ", stream);
777     }
778
779   if (flags->print_offsets)
780     {
781       /* Undo the temporary level increase we did above.  */
782       level -= 2;
783       podata->finish (type, level, stream);
784       print_spaces_filtered (print_offset_data::indentation, stream);
785       if (level == 0)
786         print_spaces_filtered (2, stream);
787     }
788   if (!for_rust_enum || flags->print_offsets)
789     print_spaces_filtered (level, stream);
790   fputs_filtered (is_tuple_struct ? ")" : "}", stream);
791 }
792
793 /* la_print_typedef implementation for Rust.  */
794
795 static void
796 rust_print_typedef (struct type *type,
797                     struct symbol *new_symbol,
798                     struct ui_file *stream)
799 {
800   type = check_typedef (type);
801   fprintf_filtered (stream, "type %s = ", SYMBOL_PRINT_NAME (new_symbol));
802   type_print (type, "", stream, 0);
803   fprintf_filtered (stream, ";\n");
804 }
805
806 /* la_print_type implementation for Rust.  */
807
808 static void
809 rust_internal_print_type (struct type *type, const char *varstring,
810                           struct ui_file *stream, int show, int level,
811                           const struct type_print_options *flags,
812                           bool for_rust_enum, print_offset_data *podata)
813 {
814   QUIT;
815   if (show <= 0
816       && TYPE_NAME (type) != NULL)
817     {
818       /* Rust calls the unit type "void" in its debuginfo,
819          but we don't want to print it as that.  */
820       if (TYPE_CODE (type) == TYPE_CODE_VOID)
821         fputs_filtered ("()", stream);
822       else
823         fputs_filtered (TYPE_NAME (type), stream);
824       return;
825     }
826
827   type = check_typedef (type);
828   switch (TYPE_CODE (type))
829     {
830     case TYPE_CODE_VOID:
831       /* If we have an enum, we've already printed the type's
832          unqualified name, and there is nothing else to print
833          here.  */
834       if (!for_rust_enum)
835         fputs_filtered ("()", stream);
836       break;
837
838     case TYPE_CODE_FUNC:
839       /* Delegate varargs to the C printer.  */
840       if (TYPE_VARARGS (type))
841         goto c_printer;
842
843       fputs_filtered ("fn ", stream);
844       if (varstring != NULL)
845         fputs_filtered (varstring, stream);
846       fputs_filtered ("(", stream);
847       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
848         {
849           QUIT;
850           if (i > 0)
851             fputs_filtered (", ", stream);
852           rust_internal_print_type (TYPE_FIELD_TYPE (type, i), "", stream,
853                                     -1, 0, flags, false, podata);
854         }
855       fputs_filtered (")", stream);
856       /* If it returns unit, we can omit the return type.  */
857       if (TYPE_CODE (TYPE_TARGET_TYPE (type)) != TYPE_CODE_VOID)
858         {
859           fputs_filtered (" -> ", stream);
860           rust_internal_print_type (TYPE_TARGET_TYPE (type), "", stream,
861                                     -1, 0, flags, false, podata);
862         }
863       break;
864
865     case TYPE_CODE_ARRAY:
866       {
867         LONGEST low_bound, high_bound;
868
869         fputs_filtered ("[", stream);
870         rust_internal_print_type (TYPE_TARGET_TYPE (type), NULL,
871                                   stream, show - 1, level, flags, false,
872                                   podata);
873
874         if (TYPE_HIGH_BOUND_KIND (TYPE_INDEX_TYPE (type)) == PROP_LOCEXPR
875             || TYPE_HIGH_BOUND_KIND (TYPE_INDEX_TYPE (type)) == PROP_LOCLIST)
876           fprintf_filtered (stream, "; variable length");
877         else if (get_array_bounds (type, &low_bound, &high_bound))
878           fprintf_filtered (stream, "; %s",
879                             plongest (high_bound - low_bound + 1));
880         fputs_filtered ("]", stream);
881       }
882       break;
883
884     case TYPE_CODE_UNION:
885     case TYPE_CODE_STRUCT:
886       rust_print_struct_def (type, varstring, stream, show, level, flags,
887                              for_rust_enum, podata);
888       break;
889
890     case TYPE_CODE_ENUM:
891       {
892         int len = 0;
893
894         fputs_filtered ("enum ", stream);
895         if (TYPE_NAME (type) != NULL)
896           {
897             fputs_filtered (TYPE_NAME (type), stream);
898             fputs_filtered (" ", stream);
899             len = strlen (TYPE_NAME (type));
900           }
901         fputs_filtered ("{\n", stream);
902
903         for (int i = 0; i < TYPE_NFIELDS (type); ++i)
904           {
905             const char *name = TYPE_FIELD_NAME (type, i);
906
907             QUIT;
908
909             if (len > 0
910                 && strncmp (name, TYPE_NAME (type), len) == 0
911                 && name[len] == ':'
912                 && name[len + 1] == ':')
913               name += len + 2;
914             fprintfi_filtered (level + 2, stream, "%s,\n", name);
915           }
916
917         fputs_filtered ("}", stream);
918       }
919       break;
920
921     case TYPE_CODE_PTR:
922       {
923         if (TYPE_NAME (type) != nullptr)
924           fputs_filtered (TYPE_NAME (type), stream);
925         else
926           {
927             /* We currently can't distinguish between pointers and
928                references.  */
929             fputs_filtered ("*mut ", stream);
930             type_print (TYPE_TARGET_TYPE (type), "", stream, 0);
931           }
932       }
933       break;
934
935     default:
936     c_printer:
937       c_print_type (type, varstring, stream, show, level, flags);
938     }
939 }
940
941 static void
942 rust_print_type (struct type *type, const char *varstring,
943                  struct ui_file *stream, int show, int level,
944                  const struct type_print_options *flags)
945 {
946   print_offset_data podata;
947   rust_internal_print_type (type, varstring, stream, show, level,
948                             flags, false, &podata);
949 }
950
951 \f
952
953 /* Like arch_composite_type, but uses TYPE to decide how to allocate
954    -- either on an obstack or on a gdbarch.  */
955
956 static struct type *
957 rust_composite_type (struct type *original,
958                      const char *name,
959                      const char *field1, struct type *type1,
960                      const char *field2, struct type *type2)
961 {
962   struct type *result = alloc_type_copy (original);
963   int i, nfields, bitpos;
964
965   nfields = 0;
966   if (field1 != NULL)
967     ++nfields;
968   if (field2 != NULL)
969     ++nfields;
970
971   TYPE_CODE (result) = TYPE_CODE_STRUCT;
972   TYPE_NAME (result) = name;
973
974   TYPE_NFIELDS (result) = nfields;
975   TYPE_FIELDS (result)
976     = (struct field *) TYPE_ZALLOC (result, nfields * sizeof (struct field));
977
978   i = 0;
979   bitpos = 0;
980   if (field1 != NULL)
981     {
982       struct field *field = &TYPE_FIELD (result, i);
983
984       SET_FIELD_BITPOS (*field, bitpos);
985       bitpos += TYPE_LENGTH (type1) * TARGET_CHAR_BIT;
986
987       FIELD_NAME (*field) = field1;
988       FIELD_TYPE (*field) = type1;
989       ++i;
990     }
991   if (field2 != NULL)
992     {
993       struct field *field = &TYPE_FIELD (result, i);
994       unsigned align = type_align (type2);
995
996       if (align != 0)
997         {
998           int delta;
999
1000           align *= TARGET_CHAR_BIT;
1001           delta = bitpos % align;
1002           if (delta != 0)
1003             bitpos += align - delta;
1004         }
1005       SET_FIELD_BITPOS (*field, bitpos);
1006
1007       FIELD_NAME (*field) = field2;
1008       FIELD_TYPE (*field) = type2;
1009       ++i;
1010     }
1011
1012   if (i > 0)
1013     TYPE_LENGTH (result)
1014       = (TYPE_FIELD_BITPOS (result, i - 1) / TARGET_CHAR_BIT +
1015          TYPE_LENGTH (TYPE_FIELD_TYPE (result, i - 1)));
1016   return result;
1017 }
1018
1019 /* See rust-lang.h.  */
1020
1021 struct type *
1022 rust_slice_type (const char *name, struct type *elt_type,
1023                  struct type *usize_type)
1024 {
1025   struct type *type;
1026
1027   elt_type = lookup_pointer_type (elt_type);
1028   type = rust_composite_type (elt_type, name,
1029                               "data_ptr", elt_type,
1030                               "length", usize_type);
1031
1032   return type;
1033 }
1034
1035 enum rust_primitive_types
1036 {
1037   rust_primitive_bool,
1038   rust_primitive_char,
1039   rust_primitive_i8,
1040   rust_primitive_u8,
1041   rust_primitive_i16,
1042   rust_primitive_u16,
1043   rust_primitive_i32,
1044   rust_primitive_u32,
1045   rust_primitive_i64,
1046   rust_primitive_u64,
1047   rust_primitive_isize,
1048   rust_primitive_usize,
1049   rust_primitive_f32,
1050   rust_primitive_f64,
1051   rust_primitive_unit,
1052   rust_primitive_str,
1053   nr_rust_primitive_types
1054 };
1055
1056 /* la_language_arch_info implementation for Rust.  */
1057
1058 static void
1059 rust_language_arch_info (struct gdbarch *gdbarch,
1060                          struct language_arch_info *lai)
1061 {
1062   const struct builtin_type *builtin = builtin_type (gdbarch);
1063   struct type *tem;
1064   struct type **types;
1065   unsigned int length;
1066
1067   types = GDBARCH_OBSTACK_CALLOC (gdbarch, nr_rust_primitive_types + 1,
1068                                   struct type *);
1069
1070   types[rust_primitive_bool] = arch_boolean_type (gdbarch, 8, 1, "bool");
1071   types[rust_primitive_char] = arch_character_type (gdbarch, 32, 1, "char");
1072   types[rust_primitive_i8] = arch_integer_type (gdbarch, 8, 0, "i8");
1073   types[rust_primitive_u8] = arch_integer_type (gdbarch, 8, 1, "u8");
1074   types[rust_primitive_i16] = arch_integer_type (gdbarch, 16, 0, "i16");
1075   types[rust_primitive_u16] = arch_integer_type (gdbarch, 16, 1, "u16");
1076   types[rust_primitive_i32] = arch_integer_type (gdbarch, 32, 0, "i32");
1077   types[rust_primitive_u32] = arch_integer_type (gdbarch, 32, 1, "u32");
1078   types[rust_primitive_i64] = arch_integer_type (gdbarch, 64, 0, "i64");
1079   types[rust_primitive_u64] = arch_integer_type (gdbarch, 64, 1, "u64");
1080
1081   length = 8 * TYPE_LENGTH (builtin->builtin_data_ptr);
1082   types[rust_primitive_isize] = arch_integer_type (gdbarch, length, 0, "isize");
1083   types[rust_primitive_usize] = arch_integer_type (gdbarch, length, 1, "usize");
1084
1085   types[rust_primitive_f32] = arch_float_type (gdbarch, 32, "f32",
1086                                                floatformats_ieee_single);
1087   types[rust_primitive_f64] = arch_float_type (gdbarch, 64, "f64",
1088                                                floatformats_ieee_double);
1089
1090   types[rust_primitive_unit] = arch_integer_type (gdbarch, 0, 1, "()");
1091
1092   tem = make_cv_type (1, 0, types[rust_primitive_u8], NULL);
1093   types[rust_primitive_str] = rust_slice_type ("&str", tem,
1094                                                types[rust_primitive_usize]);
1095
1096   lai->primitive_type_vector = types;
1097   lai->bool_type_default = types[rust_primitive_bool];
1098   lai->string_char_type = types[rust_primitive_u8];
1099 }
1100
1101 \f
1102
1103 /* A helper for rust_evaluate_subexp that handles OP_FUNCALL.  */
1104
1105 static struct value *
1106 rust_evaluate_funcall (struct expression *exp, int *pos, enum noside noside)
1107 {
1108   int i;
1109   int num_args = exp->elts[*pos + 1].longconst;
1110   const char *method;
1111   struct value *function, *result, *arg0;
1112   struct type *type, *fn_type;
1113   const struct block *block;
1114   struct block_symbol sym;
1115
1116   /* For an ordinary function call we can simply defer to the
1117      generic implementation.  */
1118   if (exp->elts[*pos + 3].opcode != STRUCTOP_STRUCT)
1119     return evaluate_subexp_standard (NULL, exp, pos, noside);
1120
1121   /* Skip over the OP_FUNCALL and the STRUCTOP_STRUCT.  */
1122   *pos += 4;
1123   method = &exp->elts[*pos + 1].string;
1124   *pos += 3 + BYTES_TO_EXP_ELEM (exp->elts[*pos].longconst + 1);
1125
1126   /* Evaluate the argument to STRUCTOP_STRUCT, then find its
1127      type in order to look up the method.  */
1128   arg0 = evaluate_subexp (NULL_TYPE, exp, pos, noside);
1129
1130   if (noside == EVAL_SKIP)
1131     {
1132       for (i = 0; i < num_args; ++i)
1133         evaluate_subexp (NULL_TYPE, exp, pos, noside);
1134       return arg0;
1135     }
1136
1137   std::vector<struct value *> args (num_args + 1);
1138   args[0] = arg0;
1139
1140   /* We don't yet implement real Deref semantics.  */
1141   while (TYPE_CODE (value_type (args[0])) == TYPE_CODE_PTR)
1142     args[0] = value_ind (args[0]);
1143
1144   type = value_type (args[0]);
1145   if ((TYPE_CODE (type) != TYPE_CODE_STRUCT
1146        && TYPE_CODE (type) != TYPE_CODE_UNION
1147        && TYPE_CODE (type) != TYPE_CODE_ENUM)
1148       || rust_tuple_type_p (type))
1149     error (_("Method calls only supported on struct or enum types"));
1150   if (TYPE_NAME (type) == NULL)
1151     error (_("Method call on nameless type"));
1152
1153   std::string name = std::string (TYPE_NAME (type)) + "::" + method;
1154
1155   block = get_selected_block (0);
1156   sym = lookup_symbol (name.c_str (), block, VAR_DOMAIN, NULL);
1157   if (sym.symbol == NULL)
1158     error (_("Could not find function named '%s'"), name.c_str ());
1159
1160   fn_type = SYMBOL_TYPE (sym.symbol);
1161   if (TYPE_NFIELDS (fn_type) == 0)
1162     error (_("Function '%s' takes no arguments"), name.c_str ());
1163
1164   if (TYPE_CODE (TYPE_FIELD_TYPE (fn_type, 0)) == TYPE_CODE_PTR)
1165     args[0] = value_addr (args[0]);
1166
1167   function = address_of_variable (sym.symbol, block);
1168
1169   for (i = 0; i < num_args; ++i)
1170     args[i + 1] = evaluate_subexp (NULL_TYPE, exp, pos, noside);
1171
1172   if (noside == EVAL_AVOID_SIDE_EFFECTS)
1173     result = value_zero (TYPE_TARGET_TYPE (fn_type), not_lval);
1174   else
1175     result = call_function_by_hand (function, NULL, args);
1176   return result;
1177 }
1178
1179 /* A helper for rust_evaluate_subexp that handles OP_RANGE.  */
1180
1181 static struct value *
1182 rust_range (struct expression *exp, int *pos, enum noside noside)
1183 {
1184   enum range_type kind;
1185   struct value *low = NULL, *high = NULL;
1186   struct value *addrval, *result;
1187   CORE_ADDR addr;
1188   struct type *range_type;
1189   struct type *index_type;
1190   struct type *temp_type;
1191   const char *name;
1192
1193   kind = (enum range_type) longest_to_int (exp->elts[*pos + 1].longconst);
1194   *pos += 3;
1195
1196   if (kind == HIGH_BOUND_DEFAULT || kind == NONE_BOUND_DEFAULT
1197       || kind == NONE_BOUND_DEFAULT_EXCLUSIVE)
1198     low = evaluate_subexp (NULL_TYPE, exp, pos, noside);
1199   if (kind == LOW_BOUND_DEFAULT || kind == LOW_BOUND_DEFAULT_EXCLUSIVE
1200       || kind == NONE_BOUND_DEFAULT || kind == NONE_BOUND_DEFAULT_EXCLUSIVE)
1201     high = evaluate_subexp (NULL_TYPE, exp, pos, noside);
1202   bool inclusive = (kind == NONE_BOUND_DEFAULT || kind == LOW_BOUND_DEFAULT);
1203
1204   if (noside == EVAL_SKIP)
1205     return value_from_longest (builtin_type (exp->gdbarch)->builtin_int, 1);
1206
1207   if (low == NULL)
1208     {
1209       if (high == NULL)
1210         {
1211           index_type = NULL;
1212           name = "std::ops::RangeFull";
1213         }
1214       else
1215         {
1216           index_type = value_type (high);
1217           name = (inclusive
1218                   ? "std::ops::RangeToInclusive" : "std::ops::RangeTo");
1219         }
1220     }
1221   else
1222     {
1223       if (high == NULL)
1224         {
1225           index_type = value_type (low);
1226           name = "std::ops::RangeFrom";
1227         }
1228       else
1229         {
1230           if (!types_equal (value_type (low), value_type (high)))
1231             error (_("Range expression with different types"));
1232           index_type = value_type (low);
1233           name = inclusive ? "std::ops::RangeInclusive" : "std::ops::Range";
1234         }
1235     }
1236
1237   /* If we don't have an index type, just allocate this on the
1238      arch.  Here any type will do.  */
1239   temp_type = (index_type == NULL
1240                ? language_bool_type (exp->language_defn, exp->gdbarch)
1241                : index_type);
1242   /* It would be nicer to cache the range type.  */
1243   range_type = rust_composite_type (temp_type, name,
1244                                     low == NULL ? NULL : "start", index_type,
1245                                     high == NULL ? NULL : "end", index_type);
1246
1247   if (noside == EVAL_AVOID_SIDE_EFFECTS)
1248     return value_zero (range_type, lval_memory);
1249
1250   addrval = value_allocate_space_in_inferior (TYPE_LENGTH (range_type));
1251   addr = value_as_long (addrval);
1252   result = value_at_lazy (range_type, addr);
1253
1254   if (low != NULL)
1255     {
1256       struct value *start = value_struct_elt (&result, NULL, "start", NULL,
1257                                               "range");
1258
1259       value_assign (start, low);
1260     }
1261
1262   if (high != NULL)
1263     {
1264       struct value *end = value_struct_elt (&result, NULL, "end", NULL,
1265                                             "range");
1266
1267       value_assign (end, high);
1268     }
1269
1270   result = value_at_lazy (range_type, addr);
1271   return result;
1272 }
1273
1274 /* A helper function to compute the range and kind given a range
1275    value.  TYPE is the type of the range value.  RANGE is the range
1276    value.  LOW, HIGH, and KIND are out parameters.  The LOW and HIGH
1277    parameters might be filled in, or might not be, depending on the
1278    kind of range this is.  KIND will always be set to the appropriate
1279    value describing the kind of range, and this can be used to
1280    determine whether LOW or HIGH are valid.  */
1281
1282 static void
1283 rust_compute_range (struct type *type, struct value *range,
1284                     LONGEST *low, LONGEST *high,
1285                     enum range_type *kind)
1286 {
1287   int i;
1288
1289   *low = 0;
1290   *high = 0;
1291   *kind = BOTH_BOUND_DEFAULT;
1292
1293   if (TYPE_NFIELDS (type) == 0)
1294     return;
1295
1296   i = 0;
1297   if (strcmp (TYPE_FIELD_NAME (type, 0), "start") == 0)
1298     {
1299       *kind = HIGH_BOUND_DEFAULT;
1300       *low = value_as_long (value_field (range, 0));
1301       ++i;
1302     }
1303   if (TYPE_NFIELDS (type) > i
1304       && strcmp (TYPE_FIELD_NAME (type, i), "end") == 0)
1305     {
1306       *kind = (*kind == BOTH_BOUND_DEFAULT
1307                ? LOW_BOUND_DEFAULT : NONE_BOUND_DEFAULT);
1308       *high = value_as_long (value_field (range, i));
1309
1310       if (rust_inclusive_range_type_p (type))
1311         ++*high;
1312     }
1313 }
1314
1315 /* A helper for rust_evaluate_subexp that handles BINOP_SUBSCRIPT.  */
1316
1317 static struct value *
1318 rust_subscript (struct expression *exp, int *pos, enum noside noside,
1319                 int for_addr)
1320 {
1321   struct value *lhs, *rhs, *result;
1322   struct type *rhstype;
1323   LONGEST low, high_bound;
1324   /* Initialized to appease the compiler.  */
1325   enum range_type kind = BOTH_BOUND_DEFAULT;
1326   LONGEST high = 0;
1327   int want_slice = 0;
1328
1329   ++*pos;
1330   lhs = evaluate_subexp (NULL_TYPE, exp, pos, noside);
1331   rhs = evaluate_subexp (NULL_TYPE, exp, pos, noside);
1332
1333   if (noside == EVAL_SKIP)
1334     return lhs;
1335
1336   rhstype = check_typedef (value_type (rhs));
1337   if (rust_range_type_p (rhstype))
1338     {
1339       if (!for_addr)
1340         error (_("Can't take slice of array without '&'"));
1341       rust_compute_range (rhstype, rhs, &low, &high, &kind);
1342       want_slice = 1;
1343     }
1344   else
1345     low = value_as_long (rhs);
1346
1347   struct type *type = check_typedef (value_type (lhs));
1348   if (noside == EVAL_AVOID_SIDE_EFFECTS)
1349     {
1350       struct type *base_type = nullptr;
1351       if (TYPE_CODE (type) == TYPE_CODE_ARRAY)
1352         base_type = TYPE_TARGET_TYPE (type);
1353       else if (rust_slice_type_p (type))
1354         {
1355           for (int i = 0; i < TYPE_NFIELDS (type); ++i)
1356             {
1357               if (strcmp (TYPE_FIELD_NAME (type, i), "data_ptr") == 0)
1358                 {
1359                   base_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type, i));
1360                   break;
1361                 }
1362             }
1363           if (base_type == nullptr)
1364             error (_("Could not find 'data_ptr' in slice type"));
1365         }
1366       else if (TYPE_CODE (type) == TYPE_CODE_PTR)
1367         base_type = TYPE_TARGET_TYPE (type);
1368       else
1369         error (_("Cannot subscript non-array type"));
1370
1371       struct type *new_type;
1372       if (want_slice)
1373         {
1374           if (rust_slice_type_p (type))
1375             new_type = type;
1376           else
1377             {
1378               struct type *usize
1379                 = language_lookup_primitive_type (exp->language_defn,
1380                                                   exp->gdbarch,
1381                                                   "usize");
1382               new_type = rust_slice_type ("&[*gdb*]", base_type, usize);
1383             }
1384         }
1385       else
1386         new_type = base_type;
1387
1388       return value_zero (new_type, VALUE_LVAL (lhs));
1389     }
1390   else
1391     {
1392       LONGEST low_bound;
1393       struct value *base;
1394
1395       if (TYPE_CODE (type) == TYPE_CODE_ARRAY)
1396         {
1397           base = lhs;
1398           if (!get_array_bounds (type, &low_bound, &high_bound))
1399             error (_("Can't compute array bounds"));
1400           if (low_bound != 0)
1401             error (_("Found array with non-zero lower bound"));
1402           ++high_bound;
1403         }
1404       else if (rust_slice_type_p (type))
1405         {
1406           struct value *len;
1407
1408           base = value_struct_elt (&lhs, NULL, "data_ptr", NULL, "slice");
1409           len = value_struct_elt (&lhs, NULL, "length", NULL, "slice");
1410           low_bound = 0;
1411           high_bound = value_as_long (len);
1412         }
1413       else if (TYPE_CODE (type) == TYPE_CODE_PTR)
1414         {
1415           base = lhs;
1416           low_bound = 0;
1417           high_bound = LONGEST_MAX;
1418         }
1419       else
1420         error (_("Cannot subscript non-array type"));
1421
1422       if (want_slice
1423           && (kind == BOTH_BOUND_DEFAULT || kind == LOW_BOUND_DEFAULT))
1424         low = low_bound;
1425       if (low < 0)
1426         error (_("Index less than zero"));
1427       if (low > high_bound)
1428         error (_("Index greater than length"));
1429
1430       result = value_subscript (base, low);
1431     }
1432
1433   if (for_addr)
1434     {
1435       if (want_slice)
1436         {
1437           struct type *usize, *slice;
1438           CORE_ADDR addr;
1439           struct value *addrval, *tem;
1440
1441           if (kind == BOTH_BOUND_DEFAULT || kind == HIGH_BOUND_DEFAULT)
1442             high = high_bound;
1443           if (high < 0)
1444             error (_("High index less than zero"));
1445           if (low > high)
1446             error (_("Low index greater than high index"));
1447           if (high > high_bound)
1448             error (_("High index greater than length"));
1449
1450           usize = language_lookup_primitive_type (exp->language_defn,
1451                                                   exp->gdbarch,
1452                                                   "usize");
1453           const char *new_name = ((type != nullptr
1454                                    && rust_slice_type_p (type))
1455                                   ? TYPE_NAME (type) : "&[*gdb*]");
1456
1457           slice = rust_slice_type (new_name, value_type (result), usize);
1458
1459           addrval = value_allocate_space_in_inferior (TYPE_LENGTH (slice));
1460           addr = value_as_long (addrval);
1461           tem = value_at_lazy (slice, addr);
1462
1463           value_assign (value_field (tem, 0), value_addr (result));
1464           value_assign (value_field (tem, 1),
1465                         value_from_longest (usize, high - low));
1466
1467           result = value_at_lazy (slice, addr);
1468         }
1469       else
1470         result = value_addr (result);
1471     }
1472
1473   return result;
1474 }
1475
1476 /* evaluate_exp implementation for Rust.  */
1477
1478 static struct value *
1479 rust_evaluate_subexp (struct type *expect_type, struct expression *exp,
1480                       int *pos, enum noside noside)
1481 {
1482   struct value *result;
1483
1484   switch (exp->elts[*pos].opcode)
1485     {
1486     case UNOP_IND:
1487       {
1488         if (noside != EVAL_NORMAL)
1489           result = evaluate_subexp_standard (expect_type, exp, pos, noside);
1490         else
1491           {
1492             ++*pos;
1493             struct value *value = evaluate_subexp (expect_type, exp, pos,
1494                                                    noside);
1495
1496             struct value *trait_ptr = rust_get_trait_object_pointer (value);
1497             if (trait_ptr != NULL)
1498               value = trait_ptr;
1499
1500             result = value_ind (value);
1501           }
1502       }
1503       break;
1504
1505     case UNOP_COMPLEMENT:
1506       {
1507         struct value *value;
1508
1509         ++*pos;
1510         value = evaluate_subexp (NULL_TYPE, exp, pos, noside);
1511         if (noside == EVAL_SKIP)
1512           {
1513             /* Preserving the type is enough.  */
1514             return value;
1515           }
1516         if (TYPE_CODE (value_type (value)) == TYPE_CODE_BOOL)
1517           result = value_from_longest (value_type (value),
1518                                        value_logical_not (value));
1519         else
1520           result = value_complement (value);
1521       }
1522       break;
1523
1524     case BINOP_SUBSCRIPT:
1525       result = rust_subscript (exp, pos, noside, 0);
1526       break;
1527
1528     case OP_FUNCALL:
1529       result = rust_evaluate_funcall (exp, pos, noside);
1530       break;
1531
1532     case OP_AGGREGATE:
1533       {
1534         int pc = (*pos)++;
1535         struct type *type = exp->elts[pc + 1].type;
1536         int arglen = longest_to_int (exp->elts[pc + 2].longconst);
1537         int i;
1538         CORE_ADDR addr = 0;
1539         struct value *addrval = NULL;
1540
1541         *pos += 3;
1542
1543         if (noside == EVAL_NORMAL)
1544           {
1545             addrval = value_allocate_space_in_inferior (TYPE_LENGTH (type));
1546             addr = value_as_long (addrval);
1547             result = value_at_lazy (type, addr);
1548           }
1549
1550         if (arglen > 0 && exp->elts[*pos].opcode == OP_OTHERS)
1551           {
1552             struct value *init;
1553
1554             ++*pos;
1555             init = rust_evaluate_subexp (NULL, exp, pos, noside);
1556             if (noside == EVAL_NORMAL)
1557               {
1558                 /* This isn't quite right but will do for the time
1559                    being, seeing that we can't implement the Copy
1560                    trait anyway.  */
1561                 value_assign (result, init);
1562               }
1563
1564             --arglen;
1565           }
1566
1567         gdb_assert (arglen % 2 == 0);
1568         for (i = 0; i < arglen; i += 2)
1569           {
1570             int len;
1571             const char *fieldname;
1572             struct value *value, *field;
1573
1574             gdb_assert (exp->elts[*pos].opcode == OP_NAME);
1575             ++*pos;
1576             len = longest_to_int (exp->elts[*pos].longconst);
1577             ++*pos;
1578             fieldname = &exp->elts[*pos].string;
1579             *pos += 2 + BYTES_TO_EXP_ELEM (len + 1);
1580
1581             value = rust_evaluate_subexp (NULL, exp, pos, noside);
1582             if (noside == EVAL_NORMAL)
1583               {
1584                 field = value_struct_elt (&result, NULL, fieldname, NULL,
1585                                           "structure");
1586                 value_assign (field, value);
1587               }
1588           }
1589
1590         if (noside == EVAL_SKIP)
1591           return value_from_longest (builtin_type (exp->gdbarch)->builtin_int,
1592                                      1);
1593         else if (noside == EVAL_AVOID_SIDE_EFFECTS)
1594           result = allocate_value (type);
1595         else
1596           result = value_at_lazy (type, addr);
1597       }
1598       break;
1599
1600     case OP_RUST_ARRAY:
1601       {
1602         (*pos)++;
1603         int copies;
1604         struct value *elt;
1605         struct value *ncopies;
1606
1607         elt = rust_evaluate_subexp (NULL, exp, pos, noside);
1608         ncopies = rust_evaluate_subexp (NULL, exp, pos, noside);
1609         copies = value_as_long (ncopies);
1610         if (copies < 0)
1611           error (_("Array with negative number of elements"));
1612
1613         if (noside == EVAL_NORMAL)
1614           {
1615             int i;
1616             std::vector<struct value *> eltvec (copies);
1617
1618             for (i = 0; i < copies; ++i)
1619               eltvec[i] = elt;
1620             result = value_array (0, copies - 1, eltvec.data ());
1621           }
1622         else
1623           {
1624             struct type *arraytype
1625               = lookup_array_range_type (value_type (elt), 0, copies - 1);
1626             result = allocate_value (arraytype);
1627           }
1628       }
1629       break;
1630
1631     case STRUCTOP_ANONYMOUS:
1632       {
1633         /* Anonymous field access, i.e. foo.1.  */
1634         struct value *lhs;
1635         int pc, field_number, nfields;
1636         struct type *type;
1637
1638         pc = (*pos)++;
1639         field_number = longest_to_int (exp->elts[pc + 1].longconst);
1640         (*pos) += 2;
1641         lhs = evaluate_subexp (NULL_TYPE, exp, pos, noside);
1642
1643         type = value_type (lhs);
1644
1645         if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
1646           {
1647             struct type *outer_type = NULL;
1648
1649             if (rust_enum_p (type))
1650               {
1651                 if (rust_empty_enum_p (type))
1652                   error (_("Cannot access field %d of empty enum %s"),
1653                          field_number, TYPE_NAME (type));
1654
1655                 const gdb_byte *valaddr = value_contents (lhs);
1656                 struct field *variant_field = rust_enum_variant (type, valaddr);
1657
1658                 struct value *union_value = value_primitive_field (lhs, 0, 0,
1659                                                                    type);
1660
1661                 int fieldno = (variant_field
1662                                - &TYPE_FIELD (value_type (union_value), 0));
1663                 lhs = value_primitive_field (union_value, 0, fieldno,
1664                                              value_type (union_value));
1665                 outer_type = type;
1666                 type = value_type (lhs);
1667               }
1668
1669             /* Tuples and tuple structs */
1670             nfields = TYPE_NFIELDS (type);
1671
1672             if (field_number >= nfields || field_number < 0)
1673               {
1674                 if (outer_type != NULL)
1675                   error(_("Cannot access field %d of variant %s::%s, "
1676                           "there are only %d fields"),
1677                         field_number, TYPE_NAME (outer_type),
1678                         rust_last_path_segment (TYPE_NAME (type)),
1679                         nfields);
1680                 else
1681                   error(_("Cannot access field %d of %s, "
1682                           "there are only %d fields"),
1683                         field_number, TYPE_NAME (type), nfields);
1684               }
1685
1686             /* Tuples are tuple structs too.  */
1687             if (!rust_tuple_struct_type_p (type))
1688               {
1689                 if (outer_type != NULL)
1690                   error(_("Variant %s::%s is not a tuple variant"),
1691                         TYPE_NAME (outer_type),
1692                         rust_last_path_segment (TYPE_NAME (type)));
1693                 else
1694                   error(_("Attempting to access anonymous field %d "
1695                           "of %s, which is not a tuple, tuple struct, or "
1696                           "tuple-like variant"),
1697                       field_number, TYPE_NAME (type));
1698               }
1699
1700             result = value_primitive_field (lhs, 0, field_number, type);
1701           }
1702         else
1703           error(_("Anonymous field access is only allowed on tuples, \
1704 tuple structs, and tuple-like enum variants"));
1705       }
1706       break;
1707
1708     case STRUCTOP_STRUCT:
1709       {
1710         struct value *lhs;
1711         struct type *type;
1712         int tem, pc;
1713
1714         pc = (*pos)++;
1715         tem = longest_to_int (exp->elts[pc + 1].longconst);
1716         (*pos) += 3 + BYTES_TO_EXP_ELEM (tem + 1);
1717         lhs = evaluate_subexp (NULL_TYPE, exp, pos, noside);
1718
1719         const char *field_name = &exp->elts[pc + 2].string;
1720         type = value_type (lhs);
1721         if (TYPE_CODE (type) == TYPE_CODE_STRUCT && rust_enum_p (type))
1722           {
1723             if (rust_empty_enum_p (type))
1724               error (_("Cannot access field %s of empty enum %s"),
1725                      field_name, TYPE_NAME (type));
1726
1727             const gdb_byte *valaddr = value_contents (lhs);
1728             struct field *variant_field = rust_enum_variant (type, valaddr);
1729
1730             struct value *union_value = value_primitive_field (lhs, 0, 0,
1731                                                                type);
1732
1733             int fieldno = (variant_field
1734                            - &TYPE_FIELD (value_type (union_value), 0));
1735             lhs = value_primitive_field (union_value, 0, fieldno,
1736                                          value_type (union_value));
1737
1738             struct type *outer_type = type;
1739             type = value_type (lhs);
1740             if (rust_tuple_type_p (type) || rust_tuple_struct_type_p (type))
1741                 error (_("Attempting to access named field %s of tuple "
1742                          "variant %s::%s, which has only anonymous fields"),
1743                        field_name, TYPE_NAME (outer_type),
1744                        rust_last_path_segment (TYPE_NAME (type)));
1745
1746             TRY
1747               {
1748                 result = value_struct_elt (&lhs, NULL, field_name,
1749                                            NULL, "structure");
1750               }
1751             CATCH (except, RETURN_MASK_ERROR)
1752               {
1753                 error (_("Could not find field %s of struct variant %s::%s"),
1754                        field_name, TYPE_NAME (outer_type),
1755                        rust_last_path_segment (TYPE_NAME (type)));
1756               }
1757             END_CATCH
1758           }
1759         else
1760           result = value_struct_elt (&lhs, NULL, field_name, NULL, "structure");
1761         if (noside == EVAL_AVOID_SIDE_EFFECTS)
1762           result = value_zero (value_type (result), VALUE_LVAL (result));
1763       }
1764       break;
1765
1766     case OP_RANGE:
1767       result = rust_range (exp, pos, noside);
1768       break;
1769
1770     case UNOP_ADDR:
1771       /* We might have &array[range], in which case we need to make a
1772          slice.  */
1773       if (exp->elts[*pos + 1].opcode == BINOP_SUBSCRIPT)
1774         {
1775           ++*pos;
1776           result = rust_subscript (exp, pos, noside, 1);
1777           break;
1778         }
1779       /* Fall through.  */
1780     default:
1781       result = evaluate_subexp_standard (expect_type, exp, pos, noside);
1782       break;
1783     }
1784
1785   return result;
1786 }
1787
1788 /* operator_length implementation for Rust.  */
1789
1790 static void
1791 rust_operator_length (const struct expression *exp, int pc, int *oplenp,
1792                       int *argsp)
1793 {
1794   int oplen = 1;
1795   int args = 0;
1796
1797   switch (exp->elts[pc - 1].opcode)
1798     {
1799     case OP_AGGREGATE:
1800       /* We handle aggregate as a type and argument count.  The first
1801          argument might be OP_OTHERS.  After that the arguments
1802          alternate: first an OP_NAME, then an expression.  */
1803       oplen = 4;
1804       args = longest_to_int (exp->elts[pc - 2].longconst);
1805       break;
1806
1807     case OP_OTHERS:
1808       oplen = 1;
1809       args = 1;
1810       break;
1811
1812     case STRUCTOP_ANONYMOUS:
1813       oplen = 3;
1814       args = 1;
1815       break;
1816
1817     case OP_RUST_ARRAY:
1818       oplen = 1;
1819       args = 2;
1820       break;
1821
1822     default:
1823       operator_length_standard (exp, pc, oplenp, argsp);
1824       return;
1825     }
1826
1827   *oplenp = oplen;
1828   *argsp = args;
1829 }
1830
1831 /* op_name implementation for Rust.  */
1832
1833 static const char *
1834 rust_op_name (enum exp_opcode opcode)
1835 {
1836   switch (opcode)
1837     {
1838     case OP_AGGREGATE:
1839       return "OP_AGGREGATE";
1840     case OP_OTHERS:
1841       return "OP_OTHERS";
1842     default:
1843       return op_name_standard (opcode);
1844     }
1845 }
1846
1847 /* dump_subexp_body implementation for Rust.  */
1848
1849 static int
1850 rust_dump_subexp_body (struct expression *exp, struct ui_file *stream,
1851                        int elt)
1852 {
1853   switch (exp->elts[elt].opcode)
1854     {
1855     case OP_AGGREGATE:
1856       {
1857         int length = longest_to_int (exp->elts[elt + 2].longconst);
1858         int i;
1859
1860         fprintf_filtered (stream, "Type @");
1861         gdb_print_host_address (exp->elts[elt + 1].type, stream);
1862         fprintf_filtered (stream, " (");
1863         type_print (exp->elts[elt + 1].type, NULL, stream, 0);
1864         fprintf_filtered (stream, "), length %d", length);
1865
1866         elt += 4;
1867         for (i = 0; i < length; ++i)
1868           elt = dump_subexp (exp, stream, elt);
1869       }
1870       break;
1871
1872     case OP_STRING:
1873     case OP_NAME:
1874       {
1875         LONGEST len = exp->elts[elt + 1].longconst;
1876
1877         fprintf_filtered (stream, "%s: %s",
1878                           (exp->elts[elt].opcode == OP_STRING
1879                            ? "string" : "name"),
1880                           &exp->elts[elt + 2].string);
1881         elt += 4 + BYTES_TO_EXP_ELEM (len + 1);
1882       }
1883       break;
1884
1885     case OP_OTHERS:
1886       elt = dump_subexp (exp, stream, elt + 1);
1887       break;
1888
1889     case STRUCTOP_ANONYMOUS:
1890       {
1891         int field_number;
1892
1893         field_number = longest_to_int (exp->elts[elt + 1].longconst);
1894
1895         fprintf_filtered (stream, "Field number: %d", field_number);
1896         elt = dump_subexp (exp, stream, elt + 3);
1897       }
1898       break;
1899
1900     case OP_RUST_ARRAY:
1901       ++elt;
1902       break;
1903
1904     default:
1905       elt = dump_subexp_body_standard (exp, stream, elt);
1906       break;
1907     }
1908
1909   return elt;
1910 }
1911
1912 /* print_subexp implementation for Rust.  */
1913
1914 static void
1915 rust_print_subexp (struct expression *exp, int *pos, struct ui_file *stream,
1916                    enum precedence prec)
1917 {
1918   switch (exp->elts[*pos].opcode)
1919     {
1920     case OP_AGGREGATE:
1921       {
1922         int length = longest_to_int (exp->elts[*pos + 2].longconst);
1923         int i;
1924
1925         type_print (exp->elts[*pos + 1].type, "", stream, 0);
1926         fputs_filtered (" { ", stream);
1927
1928         *pos += 4;
1929         for (i = 0; i < length; ++i)
1930           {
1931             rust_print_subexp (exp, pos, stream, prec);
1932             fputs_filtered (", ", stream);
1933           }
1934         fputs_filtered (" }", stream);
1935       }
1936       break;
1937
1938     case OP_NAME:
1939       {
1940         LONGEST len = exp->elts[*pos + 1].longconst;
1941
1942         fputs_filtered (&exp->elts[*pos + 2].string, stream);
1943         *pos += 4 + BYTES_TO_EXP_ELEM (len + 1);
1944       }
1945       break;
1946
1947     case OP_OTHERS:
1948       {
1949         fputs_filtered ("<<others>> (", stream);
1950         ++*pos;
1951         rust_print_subexp (exp, pos, stream, prec);
1952         fputs_filtered (")", stream);
1953       }
1954       break;
1955
1956     case STRUCTOP_ANONYMOUS:
1957       {
1958         int tem = longest_to_int (exp->elts[*pos + 1].longconst);
1959
1960         (*pos) += 3;
1961         print_subexp (exp, pos, stream, PREC_SUFFIX);
1962         fprintf_filtered (stream, ".%d", tem);
1963       }
1964       break;
1965
1966     case OP_RUST_ARRAY:
1967       ++*pos;
1968       fprintf_filtered (stream, "[");
1969       rust_print_subexp (exp, pos, stream, prec);
1970       fprintf_filtered (stream, "; ");
1971       rust_print_subexp (exp, pos, stream, prec);
1972       fprintf_filtered (stream, "]");
1973       break;
1974
1975     default:
1976       print_subexp_standard (exp, pos, stream, prec);
1977       break;
1978     }
1979 }
1980
1981 /* operator_check implementation for Rust.  */
1982
1983 static int
1984 rust_operator_check (struct expression *exp, int pos,
1985                      int (*objfile_func) (struct objfile *objfile,
1986                                           void *data),
1987                      void *data)
1988 {
1989   switch (exp->elts[pos].opcode)
1990     {
1991     case OP_AGGREGATE:
1992       {
1993         struct type *type = exp->elts[pos + 1].type;
1994         struct objfile *objfile = TYPE_OBJFILE (type);
1995
1996         if (objfile != NULL && (*objfile_func) (objfile, data))
1997           return 1;
1998       }
1999       break;
2000
2001     case OP_OTHERS:
2002     case OP_NAME:
2003     case OP_RUST_ARRAY:
2004       break;
2005
2006     default:
2007       return operator_check_standard (exp, pos, objfile_func, data);
2008     }
2009
2010   return 0;
2011 }
2012
2013 \f
2014
2015 /* Implementation of la_lookup_symbol_nonlocal for Rust.  */
2016
2017 static struct block_symbol
2018 rust_lookup_symbol_nonlocal (const struct language_defn *langdef,
2019                              const char *name,
2020                              const struct block *block,
2021                              const domain_enum domain)
2022 {
2023   struct block_symbol result = {NULL, NULL};
2024
2025   if (symbol_lookup_debug)
2026     {
2027       fprintf_unfiltered (gdb_stdlog,
2028                           "rust_lookup_symbol_non_local"
2029                           " (%s, %s (scope %s), %s)\n",
2030                           name, host_address_to_string (block),
2031                           block_scope (block), domain_name (domain));
2032     }
2033
2034   /* Look up bare names in the block's scope.  */
2035   std::string scopedname;
2036   if (name[cp_find_first_component (name)] == '\0')
2037     {
2038       const char *scope = block_scope (block);
2039
2040       if (scope[0] != '\0')
2041         {
2042           scopedname = std::string (scope) + "::" + name;
2043           name = scopedname.c_str ();
2044         }
2045       else
2046         name = NULL;
2047     }
2048
2049   if (name != NULL)
2050     {
2051       result = lookup_symbol_in_static_block (name, block, domain);
2052       if (result.symbol == NULL)
2053         result = lookup_global_symbol (name, block, domain);
2054     }
2055   return result;
2056 }
2057
2058 \f
2059
2060 /* la_sniff_from_mangled_name for Rust.  */
2061
2062 static int
2063 rust_sniff_from_mangled_name (const char *mangled, char **demangled)
2064 {
2065   *demangled = gdb_demangle (mangled, DMGL_PARAMS | DMGL_ANSI);
2066   return *demangled != NULL;
2067 }
2068
2069 \f
2070
2071 /* la_watch_location_expression for Rust.  */
2072
2073 static gdb::unique_xmalloc_ptr<char>
2074 rust_watch_location_expression (struct type *type, CORE_ADDR addr)
2075 {
2076   type = check_typedef (TYPE_TARGET_TYPE (check_typedef (type)));
2077   std::string name = type_to_string (type);
2078   return gdb::unique_xmalloc_ptr<char>
2079     (xstrprintf ("*(%s as *mut %s)", core_addr_to_string (addr),
2080                  name.c_str ()));
2081 }
2082
2083 \f
2084
2085 static const struct exp_descriptor exp_descriptor_rust = 
2086 {
2087   rust_print_subexp,
2088   rust_operator_length,
2089   rust_operator_check,
2090   rust_op_name,
2091   rust_dump_subexp_body,
2092   rust_evaluate_subexp
2093 };
2094
2095 static const char *rust_extensions[] =
2096 {
2097   ".rs", NULL
2098 };
2099
2100 extern const struct language_defn rust_language_defn =
2101 {
2102   "rust",
2103   "Rust",
2104   language_rust,
2105   range_check_on,
2106   case_sensitive_on,
2107   array_row_major,
2108   macro_expansion_no,
2109   rust_extensions,
2110   &exp_descriptor_rust,
2111   rust_parse,
2112   null_post_parser,
2113   rust_printchar,               /* Print a character constant */
2114   rust_printstr,                /* Function to print string constant */
2115   rust_emitchar,                /* Print a single char */
2116   rust_print_type,              /* Print a type using appropriate syntax */
2117   rust_print_typedef,           /* Print a typedef using appropriate syntax */
2118   rust_val_print,               /* Print a value using appropriate syntax */
2119   c_value_print,                /* Print a top-level value */
2120   default_read_var_value,       /* la_read_var_value */
2121   NULL,                         /* Language specific skip_trampoline */
2122   NULL,                         /* name_of_this */
2123   false,                        /* la_store_sym_names_in_linkage_form_p */
2124   rust_lookup_symbol_nonlocal,  /* lookup_symbol_nonlocal */
2125   basic_lookup_transparent_type,/* lookup_transparent_type */
2126   gdb_demangle,                 /* Language specific symbol demangler */
2127   rust_sniff_from_mangled_name,
2128   NULL,                         /* Language specific
2129                                    class_name_from_physname */
2130   c_op_print_tab,               /* expression operators for printing */
2131   1,                            /* c-style arrays */
2132   0,                            /* String lower bound */
2133   default_word_break_characters,
2134   default_collect_symbol_completion_matches,
2135   rust_language_arch_info,
2136   default_print_array_index,
2137   default_pass_by_reference,
2138   c_get_string,
2139   rust_watch_location_expression,
2140   NULL,                         /* la_get_symbol_name_matcher */
2141   iterate_over_symbols,
2142   default_search_name_hash,
2143   &default_varobj_ops,
2144   NULL,
2145   NULL,
2146   LANG_MAGIC
2147 };