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