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