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