Move lexptr and prev_lexptr to parser_state
[external/binutils.git] / gdb / rust-exp.y
1 /* Bison parser for Rust expressions, for GDB.
2    Copyright (C) 2016-2019 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 /* The Bison manual says that %pure-parser is deprecated, but we use
20    it anyway because it also works with Byacc.  That is also why
21    this uses %lex-param and %parse-param rather than the simpler
22    %param -- Byacc does not support the latter.  */
23 %pure-parser
24 %lex-param {struct rust_parser *parser}
25 %parse-param {struct rust_parser *parser}
26
27 /* Removing the last conflict seems difficult.  */
28 %expect 1
29
30 %{
31
32 #include "defs.h"
33
34 #include "block.h"
35 #include "charset.h"
36 #include "cp-support.h"
37 #include "gdb_obstack.h"
38 #include "gdb_regex.h"
39 #include "rust-lang.h"
40 #include "parser-defs.h"
41 #include "common/selftest.h"
42 #include "value.h"
43 #include "common/vec.h"
44
45 #define GDB_YY_REMAP_PREFIX rust
46 #include "yy-remap.h"
47
48 #define RUSTSTYPE YYSTYPE
49
50 struct rust_op;
51 typedef std::vector<const struct rust_op *> rust_op_vector;
52
53 /* A typed integer constant.  */
54
55 struct typed_val_int
56 {
57   LONGEST val;
58   struct type *type;
59 };
60
61 /* A typed floating point constant.  */
62
63 struct typed_val_float
64 {
65   gdb_byte val[16];
66   struct type *type;
67 };
68
69 /* An identifier and an expression.  This is used to represent one
70    element of a struct initializer.  */
71
72 struct set_field
73 {
74   struct stoken name;
75   const struct rust_op *init;
76 };
77
78 typedef std::vector<set_field> rust_set_vector;
79
80 %}
81
82 %union
83 {
84   /* A typed integer constant.  */
85   struct typed_val_int typed_val_int;
86
87   /* A typed floating point constant.  */
88   struct typed_val_float typed_val_float;
89
90   /* An identifier or string.  */
91   struct stoken sval;
92
93   /* A token representing an opcode, like "==".  */
94   enum exp_opcode opcode;
95
96   /* A list of expressions; for example, the arguments to a function
97      call.  */
98   rust_op_vector *params;
99
100   /* A list of field initializers.  */
101   rust_set_vector *field_inits;
102
103   /* A single field initializer.  */
104   struct set_field one_field_init;
105
106   /* An expression.  */
107   const struct rust_op *op;
108
109   /* A plain integer, for example used to count the number of
110      "super::" prefixes on a path.  */
111   unsigned int depth;
112 }
113
114 %{
115
116 struct rust_parser;
117 static int rustyylex (YYSTYPE *, rust_parser *);
118 static void rustyyerror (rust_parser *parser, const char *msg);
119
120 static struct stoken make_stoken (const char *);
121 static struct block_symbol rust_lookup_symbol (const char *name,
122                                                const struct block *block,
123                                                const domain_enum domain);
124
125 /* A regular expression for matching Rust numbers.  This is split up
126    since it is very long and this gives us a way to comment the
127    sections.  */
128
129 static const char *number_regex_text =
130   /* subexpression 1: allows use of alternation, otherwise uninteresting */
131   "^("
132   /* First comes floating point.  */
133   /* Recognize number after the decimal point, with optional
134      exponent and optional type suffix.
135      subexpression 2: allows "?", otherwise uninteresting
136      subexpression 3: if present, type suffix
137   */
138   "[0-9][0-9_]*\\.[0-9][0-9_]*([eE][-+]?[0-9][0-9_]*)?(f32|f64)?"
139 #define FLOAT_TYPE1 3
140   "|"
141   /* Recognize exponent without decimal point, with optional type
142      suffix.
143      subexpression 4: if present, type suffix
144   */
145 #define FLOAT_TYPE2 4
146   "[0-9][0-9_]*[eE][-+]?[0-9][0-9_]*(f32|f64)?"
147   "|"
148   /* "23." is a valid floating point number, but "23.e5" and
149      "23.f32" are not.  So, handle the trailing-. case
150      separately.  */
151   "[0-9][0-9_]*\\."
152   "|"
153   /* Finally come integers.
154      subexpression 5: text of integer
155      subexpression 6: if present, type suffix
156      subexpression 7: allows use of alternation, otherwise uninteresting
157   */
158 #define INT_TEXT 5
159 #define INT_TYPE 6
160   "(0x[a-fA-F0-9_]+|0o[0-7_]+|0b[01_]+|[0-9][0-9_]*)"
161   "([iu](size|8|16|32|64))?"
162   ")";
163 /* The number of subexpressions to allocate space for, including the
164    "0th" whole match subexpression.  */
165 #define NUM_SUBEXPRESSIONS 8
166
167 /* The compiled number-matching regex.  */
168
169 static regex_t number_regex;
170
171 /* An instance of this is created before parsing, and destroyed when
172    parsing is finished.  */
173
174 struct rust_parser
175 {
176   rust_parser (struct parser_state *state)
177     : rust_ast (nullptr),
178       pstate (state)
179   {
180   }
181
182   ~rust_parser ()
183   {
184   }
185
186   /* Create a new rust_set_vector.  The storage for the new vector is
187      managed by this class.  */
188   rust_set_vector *new_set_vector ()
189   {
190     rust_set_vector *result = new rust_set_vector;
191     set_vectors.push_back (std::unique_ptr<rust_set_vector> (result));
192     return result;
193   }
194
195   /* Create a new rust_ops_vector.  The storage for the new vector is
196      managed by this class.  */
197   rust_op_vector *new_op_vector ()
198   {
199     rust_op_vector *result = new rust_op_vector;
200     op_vectors.push_back (std::unique_ptr<rust_op_vector> (result));
201     return result;
202   }
203
204   /* Return the parser's language.  */
205   const struct language_defn *language () const
206   {
207     return pstate->language ();
208   }
209
210   /* Return the parser's gdbarch.  */
211   struct gdbarch *arch () const
212   {
213     return pstate->gdbarch ();
214   }
215
216   /* A helper to look up a Rust type, or fail.  This only works for
217      types defined by rust_language_arch_info.  */
218
219   struct type *get_type (const char *name)
220   {
221     struct type *type;
222
223     type = language_lookup_primitive_type (language (), arch (), name);
224     if (type == NULL)
225       error (_("Could not find Rust type %s"), name);
226     return type;
227   }
228
229   const char *copy_name (const char *name, int len);
230   struct stoken concat3 (const char *s1, const char *s2, const char *s3);
231   const struct rust_op *crate_name (const struct rust_op *name);
232   const struct rust_op *super_name (const struct rust_op *ident,
233                                     unsigned int n_supers);
234
235   int lex_character (YYSTYPE *lvalp);
236   int lex_number (YYSTYPE *lvalp);
237   int lex_string (YYSTYPE *lvalp);
238   int lex_identifier (YYSTYPE *lvalp);
239   uint32_t lex_hex (int min, int max);
240   uint32_t lex_escape (int is_byte);
241   int lex_operator (YYSTYPE *lvalp);
242   void push_back (char c);
243
244   struct type *rust_lookup_type (const char *name, const struct block *block);
245   std::vector<struct type *> convert_params_to_types (rust_op_vector *params);
246   struct type *convert_ast_to_type (const struct rust_op *operation);
247   const char *convert_name (const struct rust_op *operation);
248   void convert_params_to_expression (rust_op_vector *params,
249                                      const struct rust_op *top);
250   void convert_ast_to_expression (const struct rust_op *operation,
251                                   const struct rust_op *top,
252                                   bool want_type = false);
253
254   struct rust_op *ast_basic_type (enum type_code typecode);
255   const struct rust_op *ast_operation (enum exp_opcode opcode,
256                                        const struct rust_op *left,
257                                        const struct rust_op *right);
258   const struct rust_op *ast_compound_assignment
259   (enum exp_opcode opcode, const struct rust_op *left,
260    const struct rust_op *rust_op);
261   const struct rust_op *ast_literal (struct typed_val_int val);
262   const struct rust_op *ast_dliteral (struct typed_val_float val);
263   const struct rust_op *ast_structop (const struct rust_op *left,
264                                       const char *name,
265                                       int completing);
266   const struct rust_op *ast_structop_anonymous
267   (const struct rust_op *left, struct typed_val_int number);
268   const struct rust_op *ast_unary (enum exp_opcode opcode,
269                                    const struct rust_op *expr);
270   const struct rust_op *ast_cast (const struct rust_op *expr,
271                                   const struct rust_op *type);
272   const struct rust_op *ast_call_ish (enum exp_opcode opcode,
273                                       const struct rust_op *expr,
274                                       rust_op_vector *params);
275   const struct rust_op *ast_path (struct stoken name,
276                                   rust_op_vector *params);
277   const struct rust_op *ast_string (struct stoken str);
278   const struct rust_op *ast_struct (const struct rust_op *name,
279                                     rust_set_vector *fields);
280   const struct rust_op *ast_range (const struct rust_op *lhs,
281                                    const struct rust_op *rhs,
282                                    bool inclusive);
283   const struct rust_op *ast_array_type (const struct rust_op *lhs,
284                                         struct typed_val_int val);
285   const struct rust_op *ast_slice_type (const struct rust_op *type);
286   const struct rust_op *ast_reference_type (const struct rust_op *type);
287   const struct rust_op *ast_pointer_type (const struct rust_op *type,
288                                           int is_mut);
289   const struct rust_op *ast_function_type (const struct rust_op *result,
290                                            rust_op_vector *params);
291   const struct rust_op *ast_tuple_type (rust_op_vector *params);
292
293
294   /* A pointer to this is installed globally.  */
295   auto_obstack obstack;
296
297   /* Result of parsing.  Points into obstack.  */
298   const struct rust_op *rust_ast;
299
300   /* This keeps track of the various vectors we allocate.  */
301   std::vector<std::unique_ptr<rust_set_vector>> set_vectors;
302   std::vector<std::unique_ptr<rust_op_vector>> op_vectors;
303
304   /* The parser state gdb gave us.  */
305   struct parser_state *pstate;
306
307   /* Depth of parentheses.  */
308   int paren_depth = 0;
309 };
310
311 /* Rust AST operations.  We build a tree of these; then lower them to
312    gdb expressions when parsing has completed.  */
313
314 struct rust_op
315 {
316   /* The opcode.  */
317   enum exp_opcode opcode;
318   /* If OPCODE is OP_TYPE, then this holds information about what type
319      is described by this node.  */
320   enum type_code typecode;
321   /* Indicates whether OPCODE actually represents a compound
322      assignment.  For example, if OPCODE is GTGT and this is false,
323      then this rust_op represents an ordinary ">>"; but if this is
324      true, then this rust_op represents ">>=".  Unused in other
325      cases.  */
326   unsigned int compound_assignment : 1;
327   /* Only used by a field expression; if set, indicates that the field
328      name occurred at the end of the expression and is eligible for
329      completion.  */
330   unsigned int completing : 1;
331   /* For OP_RANGE, indicates whether the range is inclusive or
332      exclusive.  */
333   unsigned int inclusive : 1;
334   /* Operands of expression.  Which one is used and how depends on the
335      particular opcode.  */
336   RUSTSTYPE left;
337   RUSTSTYPE right;
338 };
339
340 %}
341
342 %token <sval> GDBVAR
343 %token <sval> IDENT
344 %token <sval> COMPLETE
345 %token <typed_val_int> INTEGER
346 %token <typed_val_int> DECIMAL_INTEGER
347 %token <sval> STRING
348 %token <sval> BYTESTRING
349 %token <typed_val_float> FLOAT
350 %token <opcode> COMPOUND_ASSIGN
351
352 /* Keyword tokens.  */
353 %token <voidval> KW_AS
354 %token <voidval> KW_IF
355 %token <voidval> KW_TRUE
356 %token <voidval> KW_FALSE
357 %token <voidval> KW_SUPER
358 %token <voidval> KW_SELF
359 %token <voidval> KW_MUT
360 %token <voidval> KW_EXTERN
361 %token <voidval> KW_CONST
362 %token <voidval> KW_FN
363 %token <voidval> KW_SIZEOF
364
365 /* Operator tokens.  */
366 %token <voidval> DOTDOT
367 %token <voidval> DOTDOTEQ
368 %token <voidval> OROR
369 %token <voidval> ANDAND
370 %token <voidval> EQEQ
371 %token <voidval> NOTEQ
372 %token <voidval> LTEQ
373 %token <voidval> GTEQ
374 %token <voidval> LSH RSH
375 %token <voidval> COLONCOLON
376 %token <voidval> ARROW
377
378 %type <op> type
379 %type <op> path_for_expr
380 %type <op> identifier_path_for_expr
381 %type <op> path_for_type
382 %type <op> identifier_path_for_type
383 %type <op> just_identifiers_for_type
384
385 %type <params> maybe_type_list
386 %type <params> type_list
387
388 %type <depth> super_path
389
390 %type <op> literal
391 %type <op> expr
392 %type <op> field_expr
393 %type <op> idx_expr
394 %type <op> unop_expr
395 %type <op> binop_expr
396 %type <op> binop_expr_expr
397 %type <op> type_cast_expr
398 %type <op> assignment_expr
399 %type <op> compound_assignment_expr
400 %type <op> paren_expr
401 %type <op> call_expr
402 %type <op> path_expr
403 %type <op> tuple_expr
404 %type <op> unit_expr
405 %type <op> struct_expr
406 %type <op> array_expr
407 %type <op> range_expr
408
409 %type <params> expr_list
410 %type <params> maybe_expr_list
411 %type <params> paren_expr_list
412
413 %type <field_inits> struct_expr_list
414 %type <one_field_init> struct_expr_tail
415
416 /* Precedence.  */
417 %nonassoc DOTDOT DOTDOTEQ
418 %right '=' COMPOUND_ASSIGN
419 %left OROR
420 %left ANDAND
421 %nonassoc EQEQ NOTEQ '<' '>' LTEQ GTEQ
422 %left '|'
423 %left '^'
424 %left '&'
425 %left LSH RSH
426 %left '@'
427 %left '+' '-'
428 %left '*' '/' '%'
429 /* These could be %precedence in Bison, but that isn't a yacc
430    feature.  */
431 %left KW_AS
432 %left UNARY
433 %left '[' '.' '('
434
435 %%
436
437 start:
438         expr
439                 {
440                   /* If we are completing and see a valid parse,
441                      rust_ast will already have been set.  */
442                   if (parser->rust_ast == NULL)
443                     parser->rust_ast = $1;
444                 }
445 ;
446
447 /* Note that the Rust grammar includes a method_call_expr, but we
448    handle this differently, to avoid a shift/reduce conflict with
449    call_expr.  */
450 expr:
451         literal
452 |       path_expr
453 |       tuple_expr
454 |       unit_expr
455 |       struct_expr
456 |       field_expr
457 |       array_expr
458 |       idx_expr
459 |       range_expr
460 |       unop_expr /* Must precede call_expr because of ambiguity with
461                      sizeof.  */
462 |       binop_expr
463 |       paren_expr
464 |       call_expr
465 ;
466
467 tuple_expr:
468         '(' expr ',' maybe_expr_list ')'
469                 {
470                   $4->push_back ($2);
471                   error (_("Tuple expressions not supported yet"));
472                 }
473 ;
474
475 unit_expr:
476         '(' ')'
477                 {
478                   struct typed_val_int val;
479
480                   val.type
481                     = (language_lookup_primitive_type
482                        (parser->language (), parser->arch (),
483                         "()"));
484                   val.val = 0;
485                   $$ = parser->ast_literal (val);
486                 }
487 ;
488
489 /* To avoid a shift/reduce conflict with call_expr, we don't handle
490    tuple struct expressions here, but instead when examining the
491    AST.  */
492 struct_expr:
493         path_for_expr '{' struct_expr_list '}'
494                 { $$ = parser->ast_struct ($1, $3); }
495 ;
496
497 struct_expr_tail:
498         DOTDOT expr
499                 {
500                   struct set_field sf;
501
502                   sf.name.ptr = NULL;
503                   sf.name.length = 0;
504                   sf.init = $2;
505
506                   $$ = sf;
507                 }
508 |       IDENT ':' expr
509                 {
510                   struct set_field sf;
511
512                   sf.name = $1;
513                   sf.init = $3;
514                   $$ = sf;
515                 }
516 |       IDENT
517                 {
518                   struct set_field sf;
519
520                   sf.name = $1;
521                   sf.init = parser->ast_path ($1, NULL);
522                   $$ = sf;
523                 }
524 ;
525
526 struct_expr_list:
527         /* %empty */
528                 {
529                   $$ = parser->new_set_vector ();
530                 }
531 |       struct_expr_tail
532                 {
533                   rust_set_vector *result = parser->new_set_vector ();
534                   result->push_back ($1);
535                   $$ = result;
536                 }
537 |       IDENT ':' expr ',' struct_expr_list
538                 {
539                   struct set_field sf;
540
541                   sf.name = $1;
542                   sf.init = $3;
543                   $5->push_back (sf);
544                   $$ = $5;
545                 }
546 |       IDENT ',' struct_expr_list
547                 {
548                   struct set_field sf;
549
550                   sf.name = $1;
551                   sf.init = parser->ast_path ($1, NULL);
552                   $3->push_back (sf);
553                   $$ = $3;
554                 }
555 ;
556
557 array_expr:
558         '[' KW_MUT expr_list ']'
559                 { $$ = parser->ast_call_ish (OP_ARRAY, NULL, $3); }
560 |       '[' expr_list ']'
561                 { $$ = parser->ast_call_ish (OP_ARRAY, NULL, $2); }
562 |       '[' KW_MUT expr ';' expr ']'
563                 { $$ = parser->ast_operation (OP_RUST_ARRAY, $3, $5); }
564 |       '[' expr ';' expr ']'
565                 { $$ = parser->ast_operation (OP_RUST_ARRAY, $2, $4); }
566 ;
567
568 range_expr:
569         expr DOTDOT
570                 { $$ = parser->ast_range ($1, NULL, false); }
571 |       expr DOTDOT expr
572                 { $$ = parser->ast_range ($1, $3, false); }
573 |       expr DOTDOTEQ expr
574                 { $$ = parser->ast_range ($1, $3, true); }
575 |       DOTDOT expr
576                 { $$ = parser->ast_range (NULL, $2, false); }
577 |       DOTDOTEQ expr
578                 { $$ = parser->ast_range (NULL, $2, true); }
579 |       DOTDOT
580                 { $$ = parser->ast_range (NULL, NULL, false); }
581 ;
582
583 literal:
584         INTEGER
585                 { $$ = parser->ast_literal ($1); }
586 |       DECIMAL_INTEGER
587                 { $$ = parser->ast_literal ($1); }
588 |       FLOAT
589                 { $$ = parser->ast_dliteral ($1); }
590 |       STRING
591                 {
592                   struct set_field field;
593                   struct typed_val_int val;
594                   struct stoken token;
595
596                   rust_set_vector *fields = parser->new_set_vector ();
597
598                   /* Wrap the raw string in the &str struct.  */
599                   field.name.ptr = "data_ptr";
600                   field.name.length = strlen (field.name.ptr);
601                   field.init = parser->ast_unary (UNOP_ADDR,
602                                                   parser->ast_string ($1));
603                   fields->push_back (field);
604
605                   val.type = parser->get_type ("usize");
606                   val.val = $1.length;
607
608                   field.name.ptr = "length";
609                   field.name.length = strlen (field.name.ptr);
610                   field.init = parser->ast_literal (val);
611                   fields->push_back (field);
612
613                   token.ptr = "&str";
614                   token.length = strlen (token.ptr);
615                   $$ = parser->ast_struct (parser->ast_path (token, NULL),
616                                            fields);
617                 }
618 |       BYTESTRING
619                 { $$ = parser->ast_string ($1); }
620 |       KW_TRUE
621                 {
622                   struct typed_val_int val;
623
624                   val.type = language_bool_type (parser->language (),
625                                                  parser->arch ());
626                   val.val = 1;
627                   $$ = parser->ast_literal (val);
628                 }
629 |       KW_FALSE
630                 {
631                   struct typed_val_int val;
632
633                   val.type = language_bool_type (parser->language (),
634                                                  parser->arch ());
635                   val.val = 0;
636                   $$ = parser->ast_literal (val);
637                 }
638 ;
639
640 field_expr:
641         expr '.' IDENT
642                 { $$ = parser->ast_structop ($1, $3.ptr, 0); }
643 |       expr '.' COMPLETE
644                 {
645                   $$ = parser->ast_structop ($1, $3.ptr, 1);
646                   parser->rust_ast = $$;
647                 }
648 |       expr '.' DECIMAL_INTEGER
649                 { $$ = parser->ast_structop_anonymous ($1, $3); }
650 ;
651
652 idx_expr:
653         expr '[' expr ']'
654                 { $$ = parser->ast_operation (BINOP_SUBSCRIPT, $1, $3); }
655 ;
656
657 unop_expr:
658         '+' expr        %prec UNARY
659                 { $$ = parser->ast_unary (UNOP_PLUS, $2); }
660
661 |       '-' expr        %prec UNARY
662                 { $$ = parser->ast_unary (UNOP_NEG, $2); }
663
664 |       '!' expr        %prec UNARY
665                 {
666                   /* Note that we provide a Rust-specific evaluator
667                      override for UNOP_COMPLEMENT, so it can do the
668                      right thing for both bool and integral
669                      values.  */
670                   $$ = parser->ast_unary (UNOP_COMPLEMENT, $2);
671                 }
672
673 |       '*' expr        %prec UNARY
674                 { $$ = parser->ast_unary (UNOP_IND, $2); }
675
676 |       '&' expr        %prec UNARY
677                 { $$ = parser->ast_unary (UNOP_ADDR, $2); }
678
679 |       '&' KW_MUT expr %prec UNARY
680                 { $$ = parser->ast_unary (UNOP_ADDR, $3); }
681 |       KW_SIZEOF '(' expr ')' %prec UNARY
682                 { $$ = parser->ast_unary (UNOP_SIZEOF, $3); }
683 ;
684
685 binop_expr:
686         binop_expr_expr
687 |       type_cast_expr
688 |       assignment_expr
689 |       compound_assignment_expr
690 ;
691
692 binop_expr_expr:
693         expr '*' expr
694                 { $$ = parser->ast_operation (BINOP_MUL, $1, $3); }
695
696 |       expr '@' expr
697                 { $$ = parser->ast_operation (BINOP_REPEAT, $1, $3); }
698
699 |       expr '/' expr
700                 { $$ = parser->ast_operation (BINOP_DIV, $1, $3); }
701
702 |       expr '%' expr
703                 { $$ = parser->ast_operation (BINOP_REM, $1, $3); }
704
705 |       expr '<' expr
706                 { $$ = parser->ast_operation (BINOP_LESS, $1, $3); }
707
708 |       expr '>' expr
709                 { $$ = parser->ast_operation (BINOP_GTR, $1, $3); }
710
711 |       expr '&' expr
712                 { $$ = parser->ast_operation (BINOP_BITWISE_AND, $1, $3); }
713
714 |       expr '|' expr
715                 { $$ = parser->ast_operation (BINOP_BITWISE_IOR, $1, $3); }
716
717 |       expr '^' expr
718                 { $$ = parser->ast_operation (BINOP_BITWISE_XOR, $1, $3); }
719
720 |       expr '+' expr
721                 { $$ = parser->ast_operation (BINOP_ADD, $1, $3); }
722
723 |       expr '-' expr
724                 { $$ = parser->ast_operation (BINOP_SUB, $1, $3); }
725
726 |       expr OROR expr
727                 { $$ = parser->ast_operation (BINOP_LOGICAL_OR, $1, $3); }
728
729 |       expr ANDAND expr
730                 { $$ = parser->ast_operation (BINOP_LOGICAL_AND, $1, $3); }
731
732 |       expr EQEQ expr
733                 { $$ = parser->ast_operation (BINOP_EQUAL, $1, $3); }
734
735 |       expr NOTEQ expr
736                 { $$ = parser->ast_operation (BINOP_NOTEQUAL, $1, $3); }
737
738 |       expr LTEQ expr
739                 { $$ = parser->ast_operation (BINOP_LEQ, $1, $3); }
740
741 |       expr GTEQ expr
742                 { $$ = parser->ast_operation (BINOP_GEQ, $1, $3); }
743
744 |       expr LSH expr
745                 { $$ = parser->ast_operation (BINOP_LSH, $1, $3); }
746
747 |       expr RSH expr
748                 { $$ = parser->ast_operation (BINOP_RSH, $1, $3); }
749 ;
750
751 type_cast_expr:
752         expr KW_AS type
753                 { $$ = parser->ast_cast ($1, $3); }
754 ;
755
756 assignment_expr:
757         expr '=' expr
758                 { $$ = parser->ast_operation (BINOP_ASSIGN, $1, $3); }
759 ;
760
761 compound_assignment_expr:
762         expr COMPOUND_ASSIGN expr
763                 { $$ = parser->ast_compound_assignment ($2, $1, $3); }
764
765 ;
766
767 paren_expr:
768         '(' expr ')'
769                 { $$ = $2; }
770 ;
771
772 expr_list:
773         expr
774                 {
775                   $$ = parser->new_op_vector ();
776                   $$->push_back ($1);
777                 }
778 |       expr_list ',' expr
779                 {
780                   $1->push_back ($3);
781                   $$ = $1;
782                 }
783 ;
784
785 maybe_expr_list:
786         /* %empty */
787                 {
788                   /* The result can't be NULL.  */
789                   $$ = parser->new_op_vector ();
790                 }
791 |       expr_list
792                 { $$ = $1; }
793 ;
794
795 paren_expr_list:
796         '(' maybe_expr_list ')'
797                 { $$ = $2; }
798 ;
799
800 call_expr:
801         expr paren_expr_list
802                 { $$ = parser->ast_call_ish (OP_FUNCALL, $1, $2); }
803 ;
804
805 maybe_self_path:
806         /* %empty */
807 |       KW_SELF COLONCOLON
808 ;
809
810 super_path:
811         KW_SUPER COLONCOLON
812                 { $$ = 1; }
813 |       super_path KW_SUPER COLONCOLON
814                 { $$ = $1 + 1; }
815 ;
816
817 path_expr:
818         path_for_expr
819                 { $$ = $1; }
820 |       GDBVAR
821                 { $$ = parser->ast_path ($1, NULL); }
822 |       KW_SELF
823                 { $$ = parser->ast_path (make_stoken ("self"), NULL); }
824 ;
825
826 path_for_expr:
827         identifier_path_for_expr
828 |       KW_SELF COLONCOLON identifier_path_for_expr
829                 { $$ = parser->super_name ($3, 0); }
830 |       maybe_self_path super_path identifier_path_for_expr
831                 { $$ = parser->super_name ($3, $2); }
832 |       COLONCOLON identifier_path_for_expr
833                 { $$ = parser->crate_name ($2); }
834 |       KW_EXTERN identifier_path_for_expr
835                 {
836                   /* This is a gdb extension to make it possible to
837                      refer to items in other crates.  It just bypasses
838                      adding the current crate to the front of the
839                      name.  */
840                   $$ = parser->ast_path (parser->concat3 ("::",
841                                                           $2->left.sval.ptr,
842                                                           NULL),
843                                          $2->right.params);
844                 }
845 ;
846
847 identifier_path_for_expr:
848         IDENT
849                 { $$ = parser->ast_path ($1, NULL); }
850 |       identifier_path_for_expr COLONCOLON IDENT
851                 {
852                   $$ = parser->ast_path (parser->concat3 ($1->left.sval.ptr,
853                                                           "::", $3.ptr),
854                                          NULL);
855                 }
856 |       identifier_path_for_expr COLONCOLON '<' type_list '>'
857                 { $$ = parser->ast_path ($1->left.sval, $4); }
858 |       identifier_path_for_expr COLONCOLON '<' type_list RSH
859                 {
860                   $$ = parser->ast_path ($1->left.sval, $4);
861                   parser->push_back ('>');
862                 }
863 ;
864
865 path_for_type:
866         identifier_path_for_type
867 |       KW_SELF COLONCOLON identifier_path_for_type
868                 { $$ = parser->super_name ($3, 0); }
869 |       maybe_self_path super_path identifier_path_for_type
870                 { $$ = parser->super_name ($3, $2); }
871 |       COLONCOLON identifier_path_for_type
872                 { $$ = parser->crate_name ($2); }
873 |       KW_EXTERN identifier_path_for_type
874                 {
875                   /* This is a gdb extension to make it possible to
876                      refer to items in other crates.  It just bypasses
877                      adding the current crate to the front of the
878                      name.  */
879                   $$ = parser->ast_path (parser->concat3 ("::",
880                                                           $2->left.sval.ptr,
881                                                           NULL),
882                                          $2->right.params);
883                 }
884 ;
885
886 just_identifiers_for_type:
887         IDENT
888                 { $$ = parser->ast_path ($1, NULL); }
889 |       just_identifiers_for_type COLONCOLON IDENT
890                 {
891                   $$ = parser->ast_path (parser->concat3 ($1->left.sval.ptr,
892                                                           "::", $3.ptr),
893                                          NULL);
894                 }
895 ;
896
897 identifier_path_for_type:
898         just_identifiers_for_type
899 |       just_identifiers_for_type '<' type_list '>'
900                 { $$ = parser->ast_path ($1->left.sval, $3); }
901 |       just_identifiers_for_type '<' type_list RSH
902                 {
903                   $$ = parser->ast_path ($1->left.sval, $3);
904                   parser->push_back ('>');
905                 }
906 ;
907
908 type:
909         path_for_type
910 |       '[' type ';' INTEGER ']'
911                 { $$ = parser->ast_array_type ($2, $4); }
912 |       '[' type ';' DECIMAL_INTEGER ']'
913                 { $$ = parser->ast_array_type ($2, $4); }
914 |       '&' '[' type ']'
915                 { $$ = parser->ast_slice_type ($3); }
916 |       '&' type
917                 { $$ = parser->ast_reference_type ($2); }
918 |       '*' KW_MUT type
919                 { $$ = parser->ast_pointer_type ($3, 1); }
920 |       '*' KW_CONST type
921                 { $$ = parser->ast_pointer_type ($3, 0); }
922 |       KW_FN '(' maybe_type_list ')' ARROW type
923                 { $$ = parser->ast_function_type ($6, $3); }
924 |       '(' maybe_type_list ')'
925                 { $$ = parser->ast_tuple_type ($2); }
926 ;
927
928 maybe_type_list:
929         /* %empty */
930                 { $$ = NULL; }
931 |       type_list
932                 { $$ = $1; }
933 ;
934
935 type_list:
936         type
937                 {
938                   rust_op_vector *result = parser->new_op_vector ();
939                   result->push_back ($1);
940                   $$ = result;
941                 }
942 |       type_list ',' type
943                 {
944                   $1->push_back ($3);
945                   $$ = $1;
946                 }
947 ;
948
949 %%
950
951 /* A struct of this type is used to describe a token.  */
952
953 struct token_info
954 {
955   const char *name;
956   int value;
957   enum exp_opcode opcode;
958 };
959
960 /* Identifier tokens.  */
961
962 static const struct token_info identifier_tokens[] =
963 {
964   { "as", KW_AS, OP_NULL },
965   { "false", KW_FALSE, OP_NULL },
966   { "if", 0, OP_NULL },
967   { "mut", KW_MUT, OP_NULL },
968   { "const", KW_CONST, OP_NULL },
969   { "self", KW_SELF, OP_NULL },
970   { "super", KW_SUPER, OP_NULL },
971   { "true", KW_TRUE, OP_NULL },
972   { "extern", KW_EXTERN, OP_NULL },
973   { "fn", KW_FN, OP_NULL },
974   { "sizeof", KW_SIZEOF, OP_NULL },
975 };
976
977 /* Operator tokens, sorted longest first.  */
978
979 static const struct token_info operator_tokens[] =
980 {
981   { ">>=", COMPOUND_ASSIGN, BINOP_RSH },
982   { "<<=", COMPOUND_ASSIGN, BINOP_LSH },
983
984   { "<<", LSH, OP_NULL },
985   { ">>", RSH, OP_NULL },
986   { "&&", ANDAND, OP_NULL },
987   { "||", OROR, OP_NULL },
988   { "==", EQEQ, OP_NULL },
989   { "!=", NOTEQ, OP_NULL },
990   { "<=", LTEQ, OP_NULL },
991   { ">=", GTEQ, OP_NULL },
992   { "+=", COMPOUND_ASSIGN, BINOP_ADD },
993   { "-=", COMPOUND_ASSIGN, BINOP_SUB },
994   { "*=", COMPOUND_ASSIGN, BINOP_MUL },
995   { "/=", COMPOUND_ASSIGN, BINOP_DIV },
996   { "%=", COMPOUND_ASSIGN, BINOP_REM },
997   { "&=", COMPOUND_ASSIGN, BINOP_BITWISE_AND },
998   { "|=", COMPOUND_ASSIGN, BINOP_BITWISE_IOR },
999   { "^=", COMPOUND_ASSIGN, BINOP_BITWISE_XOR },
1000   { "..=", DOTDOTEQ, OP_NULL },
1001
1002   { "::", COLONCOLON, OP_NULL },
1003   { "..", DOTDOT, OP_NULL },
1004   { "->", ARROW, OP_NULL }
1005 };
1006
1007 /* Helper function to copy to the name obstack.  */
1008
1009 const char *
1010 rust_parser::copy_name (const char *name, int len)
1011 {
1012   return (const char *) obstack_copy0 (&obstack, name, len);
1013 }
1014
1015 /* Helper function to make an stoken from a C string.  */
1016
1017 static struct stoken
1018 make_stoken (const char *p)
1019 {
1020   struct stoken result;
1021
1022   result.ptr = p;
1023   result.length = strlen (result.ptr);
1024   return result;
1025 }
1026
1027 /* Helper function to concatenate three strings on the name
1028    obstack.  */
1029
1030 struct stoken
1031 rust_parser::concat3 (const char *s1, const char *s2, const char *s3)
1032 {
1033   return make_stoken (obconcat (&obstack, s1, s2, s3, (char *) NULL));
1034 }
1035
1036 /* Return an AST node referring to NAME, but relative to the crate's
1037    name.  */
1038
1039 const struct rust_op *
1040 rust_parser::crate_name (const struct rust_op *name)
1041 {
1042   std::string crate = rust_crate_for_block (pstate->expression_context_block);
1043   struct stoken result;
1044
1045   gdb_assert (name->opcode == OP_VAR_VALUE);
1046
1047   if (crate.empty ())
1048     error (_("Could not find crate for current location"));
1049   result = make_stoken (obconcat (&obstack, "::", crate.c_str (), "::",
1050                                   name->left.sval.ptr, (char *) NULL));
1051
1052   return ast_path (result, name->right.params);
1053 }
1054
1055 /* Create an AST node referring to a "super::" qualified name.  IDENT
1056    is the base name and N_SUPERS is how many "super::"s were
1057    provided.  N_SUPERS can be zero.  */
1058
1059 const struct rust_op *
1060 rust_parser::super_name (const struct rust_op *ident, unsigned int n_supers)
1061 {
1062   const char *scope = block_scope (pstate->expression_context_block);
1063   int offset;
1064
1065   gdb_assert (ident->opcode == OP_VAR_VALUE);
1066
1067   if (scope[0] == '\0')
1068     error (_("Couldn't find namespace scope for self::"));
1069
1070   if (n_supers > 0)
1071     {
1072       int len;
1073       std::vector<int> offsets;
1074       unsigned int current_len;
1075
1076       current_len = cp_find_first_component (scope);
1077       while (scope[current_len] != '\0')
1078         {
1079           offsets.push_back (current_len);
1080           gdb_assert (scope[current_len] == ':');
1081           /* The "::".  */
1082           current_len += 2;
1083           current_len += cp_find_first_component (scope
1084                                                   + current_len);
1085         }
1086
1087       len = offsets.size ();
1088       if (n_supers >= len)
1089         error (_("Too many super:: uses from '%s'"), scope);
1090
1091       offset = offsets[len - n_supers];
1092     }
1093   else
1094     offset = strlen (scope);
1095
1096   obstack_grow (&obstack, "::", 2);
1097   obstack_grow (&obstack, scope, offset);
1098   obstack_grow (&obstack, "::", 2);
1099   obstack_grow0 (&obstack, ident->left.sval.ptr, ident->left.sval.length);
1100
1101   return ast_path (make_stoken ((const char *) obstack_finish (&obstack)),
1102                    ident->right.params);
1103 }
1104
1105 /* A helper that updates the innermost block as appropriate.  */
1106
1107 static void
1108 update_innermost_block (struct block_symbol sym)
1109 {
1110   if (symbol_read_needs_frame (sym.symbol))
1111     innermost_block.update (sym);
1112 }
1113
1114 /* Lex a hex number with at least MIN digits and at most MAX
1115    digits.  */
1116
1117 uint32_t
1118 rust_parser::lex_hex (int min, int max)
1119 {
1120   uint32_t result = 0;
1121   int len = 0;
1122   /* We only want to stop at MAX if we're lexing a byte escape.  */
1123   int check_max = min == max;
1124
1125   while ((check_max ? len <= max : 1)
1126          && ((pstate->lexptr[0] >= 'a' && pstate->lexptr[0] <= 'f')
1127              || (pstate->lexptr[0] >= 'A' && pstate->lexptr[0] <= 'F')
1128              || (pstate->lexptr[0] >= '0' && pstate->lexptr[0] <= '9')))
1129     {
1130       result *= 16;
1131       if (pstate->lexptr[0] >= 'a' && pstate->lexptr[0] <= 'f')
1132         result = result + 10 + pstate->lexptr[0] - 'a';
1133       else if (pstate->lexptr[0] >= 'A' && pstate->lexptr[0] <= 'F')
1134         result = result + 10 + pstate->lexptr[0] - 'A';
1135       else
1136         result = result + pstate->lexptr[0] - '0';
1137       ++pstate->lexptr;
1138       ++len;
1139     }
1140
1141   if (len < min)
1142     error (_("Not enough hex digits seen"));
1143   if (len > max)
1144     {
1145       gdb_assert (min != max);
1146       error (_("Overlong hex escape"));
1147     }
1148
1149   return result;
1150 }
1151
1152 /* Lex an escape.  IS_BYTE is true if we're lexing a byte escape;
1153    otherwise we're lexing a character escape.  */
1154
1155 uint32_t
1156 rust_parser::lex_escape (int is_byte)
1157 {
1158   uint32_t result;
1159
1160   gdb_assert (pstate->lexptr[0] == '\\');
1161   ++pstate->lexptr;
1162   switch (pstate->lexptr[0])
1163     {
1164     case 'x':
1165       ++pstate->lexptr;
1166       result = lex_hex (2, 2);
1167       break;
1168
1169     case 'u':
1170       if (is_byte)
1171         error (_("Unicode escape in byte literal"));
1172       ++pstate->lexptr;
1173       if (pstate->lexptr[0] != '{')
1174         error (_("Missing '{' in Unicode escape"));
1175       ++pstate->lexptr;
1176       result = lex_hex (1, 6);
1177       /* Could do range checks here.  */
1178       if (pstate->lexptr[0] != '}')
1179         error (_("Missing '}' in Unicode escape"));
1180       ++pstate->lexptr;
1181       break;
1182
1183     case 'n':
1184       result = '\n';
1185       ++pstate->lexptr;
1186       break;
1187     case 'r':
1188       result = '\r';
1189       ++pstate->lexptr;
1190       break;
1191     case 't':
1192       result = '\t';
1193       ++pstate->lexptr;
1194       break;
1195     case '\\':
1196       result = '\\';
1197       ++pstate->lexptr;
1198       break;
1199     case '0':
1200       result = '\0';
1201       ++pstate->lexptr;
1202       break;
1203     case '\'':
1204       result = '\'';
1205       ++pstate->lexptr;
1206       break;
1207     case '"':
1208       result = '"';
1209       ++pstate->lexptr;
1210       break;
1211
1212     default:
1213       error (_("Invalid escape \\%c in literal"), pstate->lexptr[0]);
1214     }
1215
1216   return result;
1217 }
1218
1219 /* Lex a character constant.  */
1220
1221 int
1222 rust_parser::lex_character (YYSTYPE *lvalp)
1223 {
1224   int is_byte = 0;
1225   uint32_t value;
1226
1227   if (pstate->lexptr[0] == 'b')
1228     {
1229       is_byte = 1;
1230       ++pstate->lexptr;
1231     }
1232   gdb_assert (pstate->lexptr[0] == '\'');
1233   ++pstate->lexptr;
1234   /* This should handle UTF-8 here.  */
1235   if (pstate->lexptr[0] == '\\')
1236     value = lex_escape (is_byte);
1237   else
1238     {
1239       value = pstate->lexptr[0] & 0xff;
1240       ++pstate->lexptr;
1241     }
1242
1243   if (pstate->lexptr[0] != '\'')
1244     error (_("Unterminated character literal"));
1245   ++pstate->lexptr;
1246
1247   lvalp->typed_val_int.val = value;
1248   lvalp->typed_val_int.type = get_type (is_byte ? "u8" : "char");
1249
1250   return INTEGER;
1251 }
1252
1253 /* Return the offset of the double quote if STR looks like the start
1254    of a raw string, or 0 if STR does not start a raw string.  */
1255
1256 static int
1257 starts_raw_string (const char *str)
1258 {
1259   const char *save = str;
1260
1261   if (str[0] != 'r')
1262     return 0;
1263   ++str;
1264   while (str[0] == '#')
1265     ++str;
1266   if (str[0] == '"')
1267     return str - save;
1268   return 0;
1269 }
1270
1271 /* Return true if STR looks like the end of a raw string that had N
1272    hashes at the start.  */
1273
1274 static bool
1275 ends_raw_string (const char *str, int n)
1276 {
1277   int i;
1278
1279   gdb_assert (str[0] == '"');
1280   for (i = 0; i < n; ++i)
1281     if (str[i + 1] != '#')
1282       return false;
1283   return true;
1284 }
1285
1286 /* Lex a string constant.  */
1287
1288 int
1289 rust_parser::lex_string (YYSTYPE *lvalp)
1290 {
1291   int is_byte = pstate->lexptr[0] == 'b';
1292   int raw_length;
1293
1294   if (is_byte)
1295     ++pstate->lexptr;
1296   raw_length = starts_raw_string (pstate->lexptr);
1297   pstate->lexptr += raw_length;
1298   gdb_assert (pstate->lexptr[0] == '"');
1299   ++pstate->lexptr;
1300
1301   while (1)
1302     {
1303       uint32_t value;
1304
1305       if (raw_length > 0)
1306         {
1307           if (pstate->lexptr[0] == '"' && ends_raw_string (pstate->lexptr,
1308                                                            raw_length - 1))
1309             {
1310               /* Exit with lexptr pointing after the final "#".  */
1311               pstate->lexptr += raw_length;
1312               break;
1313             }
1314           else if (pstate->lexptr[0] == '\0')
1315             error (_("Unexpected EOF in string"));
1316
1317           value = pstate->lexptr[0] & 0xff;
1318           if (is_byte && value > 127)
1319             error (_("Non-ASCII value in raw byte string"));
1320           obstack_1grow (&obstack, value);
1321
1322           ++pstate->lexptr;
1323         }
1324       else if (pstate->lexptr[0] == '"')
1325         {
1326           /* Make sure to skip the quote.  */
1327           ++pstate->lexptr;
1328           break;
1329         }
1330       else if (pstate->lexptr[0] == '\\')
1331         {
1332           value = lex_escape (is_byte);
1333
1334           if (is_byte)
1335             obstack_1grow (&obstack, value);
1336           else
1337             convert_between_encodings ("UTF-32", "UTF-8", (gdb_byte *) &value,
1338                                        sizeof (value), sizeof (value),
1339                                        &obstack, translit_none);
1340         }
1341       else if (pstate->lexptr[0] == '\0')
1342         error (_("Unexpected EOF in string"));
1343       else
1344         {
1345           value = pstate->lexptr[0] & 0xff;
1346           if (is_byte && value > 127)
1347             error (_("Non-ASCII value in byte string"));
1348           obstack_1grow (&obstack, value);
1349           ++pstate->lexptr;
1350         }
1351     }
1352
1353   lvalp->sval.length = obstack_object_size (&obstack);
1354   lvalp->sval.ptr = (const char *) obstack_finish (&obstack);
1355   return is_byte ? BYTESTRING : STRING;
1356 }
1357
1358 /* Return true if STRING starts with whitespace followed by a digit.  */
1359
1360 static bool
1361 space_then_number (const char *string)
1362 {
1363   const char *p = string;
1364
1365   while (p[0] == ' ' || p[0] == '\t')
1366     ++p;
1367   if (p == string)
1368     return false;
1369
1370   return *p >= '0' && *p <= '9';
1371 }
1372
1373 /* Return true if C can start an identifier.  */
1374
1375 static bool
1376 rust_identifier_start_p (char c)
1377 {
1378   return ((c >= 'a' && c <= 'z')
1379           || (c >= 'A' && c <= 'Z')
1380           || c == '_'
1381           || c == '$');
1382 }
1383
1384 /* Lex an identifier.  */
1385
1386 int
1387 rust_parser::lex_identifier (YYSTYPE *lvalp)
1388 {
1389   const char *start = pstate->lexptr;
1390   unsigned int length;
1391   const struct token_info *token;
1392   int i;
1393   int is_gdb_var = pstate->lexptr[0] == '$';
1394
1395   gdb_assert (rust_identifier_start_p (pstate->lexptr[0]));
1396
1397   ++pstate->lexptr;
1398
1399   /* For the time being this doesn't handle Unicode rules.  Non-ASCII
1400      identifiers are gated anyway.  */
1401   while ((pstate->lexptr[0] >= 'a' && pstate->lexptr[0] <= 'z')
1402          || (pstate->lexptr[0] >= 'A' && pstate->lexptr[0] <= 'Z')
1403          || pstate->lexptr[0] == '_'
1404          || (is_gdb_var && pstate->lexptr[0] == '$')
1405          || (pstate->lexptr[0] >= '0' && pstate->lexptr[0] <= '9'))
1406     ++pstate->lexptr;
1407
1408
1409   length = pstate->lexptr - start;
1410   token = NULL;
1411   for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
1412     {
1413       if (length == strlen (identifier_tokens[i].name)
1414           && strncmp (identifier_tokens[i].name, start, length) == 0)
1415         {
1416           token = &identifier_tokens[i];
1417           break;
1418         }
1419     }
1420
1421   if (token != NULL)
1422     {
1423       if (token->value == 0)
1424         {
1425           /* Leave the terminating token alone.  */
1426           pstate->lexptr = start;
1427           return 0;
1428         }
1429     }
1430   else if (token == NULL
1431            && (strncmp (start, "thread", length) == 0
1432                || strncmp (start, "task", length) == 0)
1433            && space_then_number (pstate->lexptr))
1434     {
1435       /* "task" or "thread" followed by a number terminates the
1436          parse, per gdb rules.  */
1437       pstate->lexptr = start;
1438       return 0;
1439     }
1440
1441   if (token == NULL || (parse_completion && pstate->lexptr[0] == '\0'))
1442     lvalp->sval = make_stoken (copy_name (start, length));
1443
1444   if (parse_completion && pstate->lexptr[0] == '\0')
1445     {
1446       /* Prevent rustyylex from returning two COMPLETE tokens.  */
1447       pstate->prev_lexptr = pstate->lexptr;
1448       return COMPLETE;
1449     }
1450
1451   if (token != NULL)
1452     return token->value;
1453   if (is_gdb_var)
1454     return GDBVAR;
1455   return IDENT;
1456 }
1457
1458 /* Lex an operator.  */
1459
1460 int
1461 rust_parser::lex_operator (YYSTYPE *lvalp)
1462 {
1463   const struct token_info *token = NULL;
1464   int i;
1465
1466   for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
1467     {
1468       if (strncmp (operator_tokens[i].name, pstate->lexptr,
1469                    strlen (operator_tokens[i].name)) == 0)
1470         {
1471           pstate->lexptr += strlen (operator_tokens[i].name);
1472           token = &operator_tokens[i];
1473           break;
1474         }
1475     }
1476
1477   if (token != NULL)
1478     {
1479       lvalp->opcode = token->opcode;
1480       return token->value;
1481     }
1482
1483   return *pstate->lexptr++;
1484 }
1485
1486 /* Lex a number.  */
1487
1488 int
1489 rust_parser::lex_number (YYSTYPE *lvalp)
1490 {
1491   regmatch_t subexps[NUM_SUBEXPRESSIONS];
1492   int match;
1493   int is_integer = 0;
1494   int could_be_decimal = 1;
1495   int implicit_i32 = 0;
1496   const char *type_name = NULL;
1497   struct type *type;
1498   int end_index;
1499   int type_index = -1;
1500   int i;
1501
1502   match = regexec (&number_regex, pstate->lexptr, ARRAY_SIZE (subexps),
1503                    subexps, 0);
1504   /* Failure means the regexp is broken.  */
1505   gdb_assert (match == 0);
1506
1507   if (subexps[INT_TEXT].rm_so != -1)
1508     {
1509       /* Integer part matched.  */
1510       is_integer = 1;
1511       end_index = subexps[INT_TEXT].rm_eo;
1512       if (subexps[INT_TYPE].rm_so == -1)
1513         {
1514           type_name = "i32";
1515           implicit_i32 = 1;
1516         }
1517       else
1518         {
1519           type_index = INT_TYPE;
1520           could_be_decimal = 0;
1521         }
1522     }
1523   else if (subexps[FLOAT_TYPE1].rm_so != -1)
1524     {
1525       /* Found floating point type suffix.  */
1526       end_index = subexps[FLOAT_TYPE1].rm_so;
1527       type_index = FLOAT_TYPE1;
1528     }
1529   else if (subexps[FLOAT_TYPE2].rm_so != -1)
1530     {
1531       /* Found floating point type suffix.  */
1532       end_index = subexps[FLOAT_TYPE2].rm_so;
1533       type_index = FLOAT_TYPE2;
1534     }
1535   else
1536     {
1537       /* Any other floating point match.  */
1538       end_index = subexps[0].rm_eo;
1539       type_name = "f64";
1540     }
1541
1542   /* We need a special case if the final character is ".".  In this
1543      case we might need to parse an integer.  For example, "23.f()" is
1544      a request for a trait method call, not a syntax error involving
1545      the floating point number "23.".  */
1546   gdb_assert (subexps[0].rm_eo > 0);
1547   if (pstate->lexptr[subexps[0].rm_eo - 1] == '.')
1548     {
1549       const char *next = skip_spaces (&pstate->lexptr[subexps[0].rm_eo]);
1550
1551       if (rust_identifier_start_p (*next) || *next == '.')
1552         {
1553           --subexps[0].rm_eo;
1554           is_integer = 1;
1555           end_index = subexps[0].rm_eo;
1556           type_name = "i32";
1557           could_be_decimal = 1;
1558           implicit_i32 = 1;
1559         }
1560     }
1561
1562   /* Compute the type name if we haven't already.  */
1563   std::string type_name_holder;
1564   if (type_name == NULL)
1565     {
1566       gdb_assert (type_index != -1);
1567       type_name_holder = std::string ((pstate->lexptr
1568                                        + subexps[type_index].rm_so),
1569                                       (subexps[type_index].rm_eo
1570                                        - subexps[type_index].rm_so));
1571       type_name = type_name_holder.c_str ();
1572     }
1573
1574   /* Look up the type.  */
1575   type = get_type (type_name);
1576
1577   /* Copy the text of the number and remove the "_"s.  */
1578   std::string number;
1579   for (i = 0; i < end_index && pstate->lexptr[i]; ++i)
1580     {
1581       if (pstate->lexptr[i] == '_')
1582         could_be_decimal = 0;
1583       else
1584         number.push_back (pstate->lexptr[i]);
1585     }
1586
1587   /* Advance past the match.  */
1588   pstate->lexptr += subexps[0].rm_eo;
1589
1590   /* Parse the number.  */
1591   if (is_integer)
1592     {
1593       uint64_t value;
1594       int radix = 10;
1595       int offset = 0;
1596
1597       if (number[0] == '0')
1598         {
1599           if (number[1] == 'x')
1600             radix = 16;
1601           else if (number[1] == 'o')
1602             radix = 8;
1603           else if (number[1] == 'b')
1604             radix = 2;
1605           if (radix != 10)
1606             {
1607               offset = 2;
1608               could_be_decimal = 0;
1609             }
1610         }
1611
1612       value = strtoul (number.c_str () + offset, NULL, radix);
1613       if (implicit_i32 && value >= ((uint64_t) 1) << 31)
1614         type = get_type ("i64");
1615
1616       lvalp->typed_val_int.val = value;
1617       lvalp->typed_val_int.type = type;
1618     }
1619   else
1620     {
1621       lvalp->typed_val_float.type = type;
1622       bool parsed = parse_float (number.c_str (), number.length (),
1623                                  lvalp->typed_val_float.type,
1624                                  lvalp->typed_val_float.val);
1625       gdb_assert (parsed);
1626     }
1627
1628   return is_integer ? (could_be_decimal ? DECIMAL_INTEGER : INTEGER) : FLOAT;
1629 }
1630
1631 /* The lexer.  */
1632
1633 static int
1634 rustyylex (YYSTYPE *lvalp, rust_parser *parser)
1635 {
1636   struct parser_state *pstate = parser->pstate;
1637
1638   /* Skip all leading whitespace.  */
1639   while (pstate->lexptr[0] == ' '
1640          || pstate->lexptr[0] == '\t'
1641          || pstate->lexptr[0] == '\r'
1642          || pstate->lexptr[0] == '\n')
1643     ++pstate->lexptr;
1644
1645   /* If we hit EOF and we're completing, then return COMPLETE -- maybe
1646      we're completing an empty string at the end of a field_expr.
1647      But, we don't want to return two COMPLETE tokens in a row.  */
1648   if (pstate->lexptr[0] == '\0' && pstate->lexptr == pstate->prev_lexptr)
1649     return 0;
1650   pstate->prev_lexptr = pstate->lexptr;
1651   if (pstate->lexptr[0] == '\0')
1652     {
1653       if (parse_completion)
1654         {
1655           lvalp->sval = make_stoken ("");
1656           return COMPLETE;
1657         }
1658       return 0;
1659     }
1660
1661   if (pstate->lexptr[0] >= '0' && pstate->lexptr[0] <= '9')
1662     return parser->lex_number (lvalp);
1663   else if (pstate->lexptr[0] == 'b' && pstate->lexptr[1] == '\'')
1664     return parser->lex_character (lvalp);
1665   else if (pstate->lexptr[0] == 'b' && pstate->lexptr[1] == '"')
1666     return parser->lex_string (lvalp);
1667   else if (pstate->lexptr[0] == 'b' && starts_raw_string (pstate->lexptr + 1))
1668     return parser->lex_string (lvalp);
1669   else if (starts_raw_string (pstate->lexptr))
1670     return parser->lex_string (lvalp);
1671   else if (rust_identifier_start_p (pstate->lexptr[0]))
1672     return parser->lex_identifier (lvalp);
1673   else if (pstate->lexptr[0] == '"')
1674     return parser->lex_string (lvalp);
1675   else if (pstate->lexptr[0] == '\'')
1676     return parser->lex_character (lvalp);
1677   else if (pstate->lexptr[0] == '}' || pstate->lexptr[0] == ']')
1678     {
1679       /* Falls through to lex_operator.  */
1680       --parser->paren_depth;
1681     }
1682   else if (pstate->lexptr[0] == '(' || pstate->lexptr[0] == '{')
1683     {
1684       /* Falls through to lex_operator.  */
1685       ++parser->paren_depth;
1686     }
1687   else if (pstate->lexptr[0] == ',' && pstate->comma_terminates
1688            && parser->paren_depth == 0)
1689     return 0;
1690
1691   return parser->lex_operator (lvalp);
1692 }
1693
1694 /* Push back a single character to be re-lexed.  */
1695
1696 void
1697 rust_parser::push_back (char c)
1698 {
1699   /* Can't be called before any lexing.  */
1700   gdb_assert (pstate->prev_lexptr != NULL);
1701
1702   --pstate->lexptr;
1703   gdb_assert (*pstate->lexptr == c);
1704 }
1705
1706 \f
1707
1708 /* Make an arbitrary operation and fill in the fields.  */
1709
1710 const struct rust_op *
1711 rust_parser::ast_operation (enum exp_opcode opcode, const struct rust_op *left,
1712                             const struct rust_op *right)
1713 {
1714   struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1715
1716   result->opcode = opcode;
1717   result->left.op = left;
1718   result->right.op = right;
1719
1720   return result;
1721 }
1722
1723 /* Make a compound assignment operation.  */
1724
1725 const struct rust_op *
1726 rust_parser::ast_compound_assignment (enum exp_opcode opcode,
1727                                       const struct rust_op *left,
1728                                       const struct rust_op *right)
1729 {
1730   struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1731
1732   result->opcode = opcode;
1733   result->compound_assignment = 1;
1734   result->left.op = left;
1735   result->right.op = right;
1736
1737   return result;
1738 }
1739
1740 /* Make a typed integer literal operation.  */
1741
1742 const struct rust_op *
1743 rust_parser::ast_literal (struct typed_val_int val)
1744 {
1745   struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1746
1747   result->opcode = OP_LONG;
1748   result->left.typed_val_int = val;
1749
1750   return result;
1751 }
1752
1753 /* Make a typed floating point literal operation.  */
1754
1755 const struct rust_op *
1756 rust_parser::ast_dliteral (struct typed_val_float val)
1757 {
1758   struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1759
1760   result->opcode = OP_FLOAT;
1761   result->left.typed_val_float = val;
1762
1763   return result;
1764 }
1765
1766 /* Make a unary operation.  */
1767
1768 const struct rust_op *
1769 rust_parser::ast_unary (enum exp_opcode opcode, const struct rust_op *expr)
1770 {
1771   return ast_operation (opcode, expr, NULL);
1772 }
1773
1774 /* Make a cast operation.  */
1775
1776 const struct rust_op *
1777 rust_parser::ast_cast (const struct rust_op *expr, const struct rust_op *type)
1778 {
1779   struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1780
1781   result->opcode = UNOP_CAST;
1782   result->left.op = expr;
1783   result->right.op = type;
1784
1785   return result;
1786 }
1787
1788 /* Make a call-like operation.  This is nominally a function call, but
1789    when lowering we may discover that it actually represents the
1790    creation of a tuple struct.  */
1791
1792 const struct rust_op *
1793 rust_parser::ast_call_ish (enum exp_opcode opcode, const struct rust_op *expr,
1794                            rust_op_vector *params)
1795 {
1796   struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1797
1798   result->opcode = opcode;
1799   result->left.op = expr;
1800   result->right.params = params;
1801
1802   return result;
1803 }
1804
1805 /* Make a structure creation operation.  */
1806
1807 const struct rust_op *
1808 rust_parser::ast_struct (const struct rust_op *name, rust_set_vector *fields)
1809 {
1810   struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1811
1812   result->opcode = OP_AGGREGATE;
1813   result->left.op = name;
1814   result->right.field_inits = fields;
1815
1816   return result;
1817 }
1818
1819 /* Make an identifier path.  */
1820
1821 const struct rust_op *
1822 rust_parser::ast_path (struct stoken path, rust_op_vector *params)
1823 {
1824   struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1825
1826   result->opcode = OP_VAR_VALUE;
1827   result->left.sval = path;
1828   result->right.params = params;
1829
1830   return result;
1831 }
1832
1833 /* Make a string constant operation.  */
1834
1835 const struct rust_op *
1836 rust_parser::ast_string (struct stoken str)
1837 {
1838   struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1839
1840   result->opcode = OP_STRING;
1841   result->left.sval = str;
1842
1843   return result;
1844 }
1845
1846 /* Make a field expression.  */
1847
1848 const struct rust_op *
1849 rust_parser::ast_structop (const struct rust_op *left, const char *name,
1850                            int completing)
1851 {
1852   struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1853
1854   result->opcode = STRUCTOP_STRUCT;
1855   result->completing = completing;
1856   result->left.op = left;
1857   result->right.sval = make_stoken (name);
1858
1859   return result;
1860 }
1861
1862 /* Make an anonymous struct operation, like 'x.0'.  */
1863
1864 const struct rust_op *
1865 rust_parser::ast_structop_anonymous (const struct rust_op *left,
1866                                      struct typed_val_int number)
1867 {
1868   struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1869
1870   result->opcode = STRUCTOP_ANONYMOUS;
1871   result->left.op = left;
1872   result->right.typed_val_int = number;
1873
1874   return result;
1875 }
1876
1877 /* Make a range operation.  */
1878
1879 const struct rust_op *
1880 rust_parser::ast_range (const struct rust_op *lhs, const struct rust_op *rhs,
1881                         bool inclusive)
1882 {
1883   struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1884
1885   result->opcode = OP_RANGE;
1886   result->inclusive = inclusive;
1887   result->left.op = lhs;
1888   result->right.op = rhs;
1889
1890   return result;
1891 }
1892
1893 /* A helper function to make a type-related AST node.  */
1894
1895 struct rust_op *
1896 rust_parser::ast_basic_type (enum type_code typecode)
1897 {
1898   struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1899
1900   result->opcode = OP_TYPE;
1901   result->typecode = typecode;
1902   return result;
1903 }
1904
1905 /* Create an AST node describing an array type.  */
1906
1907 const struct rust_op *
1908 rust_parser::ast_array_type (const struct rust_op *lhs,
1909                              struct typed_val_int val)
1910 {
1911   struct rust_op *result = ast_basic_type (TYPE_CODE_ARRAY);
1912
1913   result->left.op = lhs;
1914   result->right.typed_val_int = val;
1915   return result;
1916 }
1917
1918 /* Create an AST node describing a reference type.  */
1919
1920 const struct rust_op *
1921 rust_parser::ast_slice_type (const struct rust_op *type)
1922 {
1923   /* Use TYPE_CODE_COMPLEX just because it is handy.  */
1924   struct rust_op *result = ast_basic_type (TYPE_CODE_COMPLEX);
1925
1926   result->left.op = type;
1927   return result;
1928 }
1929
1930 /* Create an AST node describing a reference type.  */
1931
1932 const struct rust_op *
1933 rust_parser::ast_reference_type (const struct rust_op *type)
1934 {
1935   struct rust_op *result = ast_basic_type (TYPE_CODE_REF);
1936
1937   result->left.op = type;
1938   return result;
1939 }
1940
1941 /* Create an AST node describing a pointer type.  */
1942
1943 const struct rust_op *
1944 rust_parser::ast_pointer_type (const struct rust_op *type, int is_mut)
1945 {
1946   struct rust_op *result = ast_basic_type (TYPE_CODE_PTR);
1947
1948   result->left.op = type;
1949   /* For the time being we ignore is_mut.  */
1950   return result;
1951 }
1952
1953 /* Create an AST node describing a function type.  */
1954
1955 const struct rust_op *
1956 rust_parser::ast_function_type (const struct rust_op *rtype,
1957                                 rust_op_vector *params)
1958 {
1959   struct rust_op *result = ast_basic_type (TYPE_CODE_FUNC);
1960
1961   result->left.op = rtype;
1962   result->right.params = params;
1963   return result;
1964 }
1965
1966 /* Create an AST node describing a tuple type.  */
1967
1968 const struct rust_op *
1969 rust_parser::ast_tuple_type (rust_op_vector *params)
1970 {
1971   struct rust_op *result = ast_basic_type (TYPE_CODE_STRUCT);
1972
1973   result->left.params = params;
1974   return result;
1975 }
1976
1977 /* A helper to appropriately munge NAME and BLOCK depending on the
1978    presence of a leading "::".  */
1979
1980 static void
1981 munge_name_and_block (const char **name, const struct block **block)
1982 {
1983   /* If it is a global reference, skip the current block in favor of
1984      the static block.  */
1985   if (strncmp (*name, "::", 2) == 0)
1986     {
1987       *name += 2;
1988       *block = block_static_block (*block);
1989     }
1990 }
1991
1992 /* Like lookup_symbol, but handles Rust namespace conventions, and
1993    doesn't require field_of_this_result.  */
1994
1995 static struct block_symbol
1996 rust_lookup_symbol (const char *name, const struct block *block,
1997                     const domain_enum domain)
1998 {
1999   struct block_symbol result;
2000
2001   munge_name_and_block (&name, &block);
2002
2003   result = lookup_symbol (name, block, domain, NULL);
2004   if (result.symbol != NULL)
2005     update_innermost_block (result);
2006   return result;
2007 }
2008
2009 /* Look up a type, following Rust namespace conventions.  */
2010
2011 struct type *
2012 rust_parser::rust_lookup_type (const char *name, const struct block *block)
2013 {
2014   struct block_symbol result;
2015   struct type *type;
2016
2017   munge_name_and_block (&name, &block);
2018
2019   result = lookup_symbol (name, block, STRUCT_DOMAIN, NULL);
2020   if (result.symbol != NULL)
2021     {
2022       update_innermost_block (result);
2023       return SYMBOL_TYPE (result.symbol);
2024     }
2025
2026   type = lookup_typename (language (), arch (), name, NULL, 1);
2027   if (type != NULL)
2028     return type;
2029
2030   /* Last chance, try a built-in type.  */
2031   return language_lookup_primitive_type (language (), arch (), name);
2032 }
2033
2034 /* Convert a vector of rust_ops representing types to a vector of
2035    types.  */
2036
2037 std::vector<struct type *>
2038 rust_parser::convert_params_to_types (rust_op_vector *params)
2039 {
2040   std::vector<struct type *> result;
2041
2042   if (params != nullptr)
2043     {
2044       for (const rust_op *op : *params)
2045         result.push_back (convert_ast_to_type (op));
2046     }
2047
2048   return result;
2049 }
2050
2051 /* Convert a rust_op representing a type to a struct type *.  */
2052
2053 struct type *
2054 rust_parser::convert_ast_to_type (const struct rust_op *operation)
2055 {
2056   struct type *type, *result = NULL;
2057
2058   if (operation->opcode == OP_VAR_VALUE)
2059     {
2060       const char *varname = convert_name (operation);
2061
2062       result = rust_lookup_type (varname, pstate->expression_context_block);
2063       if (result == NULL)
2064         error (_("No typed name '%s' in current context"), varname);
2065       return result;
2066     }
2067
2068   gdb_assert (operation->opcode == OP_TYPE);
2069
2070   switch (operation->typecode)
2071     {
2072     case TYPE_CODE_ARRAY:
2073       type = convert_ast_to_type (operation->left.op);
2074       if (operation->right.typed_val_int.val < 0)
2075         error (_("Negative array length"));
2076       result = lookup_array_range_type (type, 0,
2077                                         operation->right.typed_val_int.val - 1);
2078       break;
2079
2080     case TYPE_CODE_COMPLEX:
2081       {
2082         struct type *usize = get_type ("usize");
2083
2084         type = convert_ast_to_type (operation->left.op);
2085         result = rust_slice_type ("&[*gdb*]", type, usize);
2086       }
2087       break;
2088
2089     case TYPE_CODE_REF:
2090     case TYPE_CODE_PTR:
2091       /* For now we treat &x and *x identically.  */
2092       type = convert_ast_to_type (operation->left.op);
2093       result = lookup_pointer_type (type);
2094       break;
2095
2096     case TYPE_CODE_FUNC:
2097       {
2098         std::vector<struct type *> args
2099           (convert_params_to_types (operation->right.params));
2100         struct type **argtypes = NULL;
2101
2102         type = convert_ast_to_type (operation->left.op);
2103         if (!args.empty ())
2104           argtypes = args.data ();
2105
2106         result
2107           = lookup_function_type_with_arguments (type, args.size (),
2108                                                  argtypes);
2109         result = lookup_pointer_type (result);
2110       }
2111       break;
2112
2113     case TYPE_CODE_STRUCT:
2114       {
2115         std::vector<struct type *> args
2116           (convert_params_to_types (operation->left.params));
2117         int i;
2118         const char *name;
2119
2120         obstack_1grow (&obstack, '(');
2121         for (i = 0; i < args.size (); ++i)
2122           {
2123             std::string type_name = type_to_string (args[i]);
2124
2125             if (i > 0)
2126               obstack_1grow (&obstack, ',');
2127             obstack_grow_str (&obstack, type_name.c_str ());
2128           }
2129
2130         obstack_grow_str0 (&obstack, ")");
2131         name = (const char *) obstack_finish (&obstack);
2132
2133         /* We don't allow creating new tuple types (yet), but we do
2134            allow looking up existing tuple types.  */
2135         result = rust_lookup_type (name, pstate->expression_context_block);
2136         if (result == NULL)
2137           error (_("could not find tuple type '%s'"), name);
2138       }
2139       break;
2140
2141     default:
2142       gdb_assert_not_reached ("unhandled opcode in convert_ast_to_type");
2143     }
2144
2145   gdb_assert (result != NULL);
2146   return result;
2147 }
2148
2149 /* A helper function to turn a rust_op representing a name into a full
2150    name.  This applies generic arguments as needed.  The returned name
2151    is allocated on the work obstack.  */
2152
2153 const char *
2154 rust_parser::convert_name (const struct rust_op *operation)
2155 {
2156   int i;
2157
2158   gdb_assert (operation->opcode == OP_VAR_VALUE);
2159
2160   if (operation->right.params == NULL)
2161     return operation->left.sval.ptr;
2162
2163   std::vector<struct type *> types
2164     (convert_params_to_types (operation->right.params));
2165
2166   obstack_grow_str (&obstack, operation->left.sval.ptr);
2167   obstack_1grow (&obstack, '<');
2168   for (i = 0; i < types.size (); ++i)
2169     {
2170       std::string type_name = type_to_string (types[i]);
2171
2172       if (i > 0)
2173         obstack_1grow (&obstack, ',');
2174
2175       obstack_grow_str (&obstack, type_name.c_str ());
2176     }
2177   obstack_grow_str0 (&obstack, ">");
2178
2179   return (const char *) obstack_finish (&obstack);
2180 }
2181
2182 /* A helper function that converts a vec of rust_ops to a gdb
2183    expression.  */
2184
2185 void
2186 rust_parser::convert_params_to_expression (rust_op_vector *params,
2187                                            const struct rust_op *top)
2188 {
2189   for (const rust_op *elem : *params)
2190     convert_ast_to_expression (elem, top);
2191 }
2192
2193 /* Lower a rust_op to a gdb expression.  STATE is the parser state.
2194    OPERATION is the operation to lower.  TOP is a pointer to the
2195    top-most operation; it is used to handle the special case where the
2196    top-most expression is an identifier and can be optionally lowered
2197    to OP_TYPE.  WANT_TYPE is a flag indicating that, if the expression
2198    is the name of a type, then emit an OP_TYPE for it (rather than
2199    erroring).  If WANT_TYPE is set, then the similar TOP handling is
2200    not done.  */
2201
2202 void
2203 rust_parser::convert_ast_to_expression (const struct rust_op *operation,
2204                                         const struct rust_op *top,
2205                                         bool want_type)
2206 {
2207   switch (operation->opcode)
2208     {
2209     case OP_LONG:
2210       write_exp_elt_opcode (pstate, OP_LONG);
2211       write_exp_elt_type (pstate, operation->left.typed_val_int.type);
2212       write_exp_elt_longcst (pstate, operation->left.typed_val_int.val);
2213       write_exp_elt_opcode (pstate, OP_LONG);
2214       break;
2215
2216     case OP_FLOAT:
2217       write_exp_elt_opcode (pstate, OP_FLOAT);
2218       write_exp_elt_type (pstate, operation->left.typed_val_float.type);
2219       write_exp_elt_floatcst (pstate, operation->left.typed_val_float.val);
2220       write_exp_elt_opcode (pstate, OP_FLOAT);
2221       break;
2222
2223     case STRUCTOP_STRUCT:
2224       {
2225         convert_ast_to_expression (operation->left.op, top);
2226
2227         if (operation->completing)
2228           mark_struct_expression (pstate);
2229         write_exp_elt_opcode (pstate, STRUCTOP_STRUCT);
2230         write_exp_string (pstate, operation->right.sval);
2231         write_exp_elt_opcode (pstate, STRUCTOP_STRUCT);
2232       }
2233       break;
2234
2235     case STRUCTOP_ANONYMOUS:
2236       {
2237         convert_ast_to_expression (operation->left.op, top);
2238
2239         write_exp_elt_opcode (pstate, STRUCTOP_ANONYMOUS);
2240         write_exp_elt_longcst (pstate, operation->right.typed_val_int.val);
2241         write_exp_elt_opcode (pstate, STRUCTOP_ANONYMOUS);
2242       }
2243       break;
2244
2245     case UNOP_SIZEOF:
2246       convert_ast_to_expression (operation->left.op, top, true);
2247       write_exp_elt_opcode (pstate, UNOP_SIZEOF);
2248       break;
2249
2250     case UNOP_PLUS:
2251     case UNOP_NEG:
2252     case UNOP_COMPLEMENT:
2253     case UNOP_IND:
2254     case UNOP_ADDR:
2255       convert_ast_to_expression (operation->left.op, top);
2256       write_exp_elt_opcode (pstate, operation->opcode);
2257       break;
2258
2259     case BINOP_SUBSCRIPT:
2260     case BINOP_MUL:
2261     case BINOP_REPEAT:
2262     case BINOP_DIV:
2263     case BINOP_REM:
2264     case BINOP_LESS:
2265     case BINOP_GTR:
2266     case BINOP_BITWISE_AND:
2267     case BINOP_BITWISE_IOR:
2268     case BINOP_BITWISE_XOR:
2269     case BINOP_ADD:
2270     case BINOP_SUB:
2271     case BINOP_LOGICAL_OR:
2272     case BINOP_LOGICAL_AND:
2273     case BINOP_EQUAL:
2274     case BINOP_NOTEQUAL:
2275     case BINOP_LEQ:
2276     case BINOP_GEQ:
2277     case BINOP_LSH:
2278     case BINOP_RSH:
2279     case BINOP_ASSIGN:
2280     case OP_RUST_ARRAY:
2281       convert_ast_to_expression (operation->left.op, top);
2282       convert_ast_to_expression (operation->right.op, top);
2283       if (operation->compound_assignment)
2284         {
2285           write_exp_elt_opcode (pstate, BINOP_ASSIGN_MODIFY);
2286           write_exp_elt_opcode (pstate, operation->opcode);
2287           write_exp_elt_opcode (pstate, BINOP_ASSIGN_MODIFY);
2288         }
2289       else
2290         write_exp_elt_opcode (pstate, operation->opcode);
2291
2292       if (operation->compound_assignment
2293           || operation->opcode == BINOP_ASSIGN)
2294         {
2295           struct type *type;
2296
2297           type = language_lookup_primitive_type (pstate->language (),
2298                                                  pstate->gdbarch (),
2299                                                  "()");
2300
2301           write_exp_elt_opcode (pstate, OP_LONG);
2302           write_exp_elt_type (pstate, type);
2303           write_exp_elt_longcst (pstate, 0);
2304           write_exp_elt_opcode (pstate, OP_LONG);
2305
2306           write_exp_elt_opcode (pstate, BINOP_COMMA);
2307         }
2308       break;
2309
2310     case UNOP_CAST:
2311       {
2312         struct type *type = convert_ast_to_type (operation->right.op);
2313
2314         convert_ast_to_expression (operation->left.op, top);
2315         write_exp_elt_opcode (pstate, UNOP_CAST);
2316         write_exp_elt_type (pstate, type);
2317         write_exp_elt_opcode (pstate, UNOP_CAST);
2318       }
2319       break;
2320
2321     case OP_FUNCALL:
2322       {
2323         if (operation->left.op->opcode == OP_VAR_VALUE)
2324           {
2325             struct type *type;
2326             const char *varname = convert_name (operation->left.op);
2327
2328             type = rust_lookup_type (varname,
2329                                      pstate->expression_context_block);
2330             if (type != NULL)
2331               {
2332                 /* This is actually a tuple struct expression, not a
2333                    call expression.  */
2334                 rust_op_vector *params = operation->right.params;
2335
2336                 if (TYPE_CODE (type) != TYPE_CODE_NAMESPACE)
2337                   {
2338                     if (!rust_tuple_struct_type_p (type))
2339                       error (_("Type %s is not a tuple struct"), varname);
2340
2341                     for (int i = 0; i < params->size (); ++i)
2342                       {
2343                         char *cell = get_print_cell ();
2344
2345                         xsnprintf (cell, PRINT_CELL_SIZE, "__%d", i);
2346                         write_exp_elt_opcode (pstate, OP_NAME);
2347                         write_exp_string (pstate, make_stoken (cell));
2348                         write_exp_elt_opcode (pstate, OP_NAME);
2349
2350                         convert_ast_to_expression ((*params)[i], top);
2351                       }
2352
2353                     write_exp_elt_opcode (pstate, OP_AGGREGATE);
2354                     write_exp_elt_type (pstate, type);
2355                     write_exp_elt_longcst (pstate, 2 * params->size ());
2356                     write_exp_elt_opcode (pstate, OP_AGGREGATE);
2357                     break;
2358                   }
2359               }
2360           }
2361         convert_ast_to_expression (operation->left.op, top);
2362         convert_params_to_expression (operation->right.params, top);
2363         write_exp_elt_opcode (pstate, OP_FUNCALL);
2364         write_exp_elt_longcst (pstate, operation->right.params->size ());
2365         write_exp_elt_longcst (pstate, OP_FUNCALL);
2366       }
2367       break;
2368
2369     case OP_ARRAY:
2370       gdb_assert (operation->left.op == NULL);
2371       convert_params_to_expression (operation->right.params, top);
2372       write_exp_elt_opcode (pstate, OP_ARRAY);
2373       write_exp_elt_longcst (pstate, 0);
2374       write_exp_elt_longcst (pstate, operation->right.params->size () - 1);
2375       write_exp_elt_longcst (pstate, OP_ARRAY);
2376       break;
2377
2378     case OP_VAR_VALUE:
2379       {
2380         struct block_symbol sym;
2381         const char *varname;
2382
2383         if (operation->left.sval.ptr[0] == '$')
2384           {
2385             write_dollar_variable (pstate, operation->left.sval);
2386             break;
2387           }
2388
2389         varname = convert_name (operation);
2390         sym = rust_lookup_symbol (varname, pstate->expression_context_block,
2391                                   VAR_DOMAIN);
2392         if (sym.symbol != NULL && SYMBOL_CLASS (sym.symbol) != LOC_TYPEDEF)
2393           {
2394             write_exp_elt_opcode (pstate, OP_VAR_VALUE);
2395             write_exp_elt_block (pstate, sym.block);
2396             write_exp_elt_sym (pstate, sym.symbol);
2397             write_exp_elt_opcode (pstate, OP_VAR_VALUE);
2398           }
2399         else
2400           {
2401             struct type *type = NULL;
2402
2403             if (sym.symbol != NULL)
2404               {
2405                 gdb_assert (SYMBOL_CLASS (sym.symbol) == LOC_TYPEDEF);
2406                 type = SYMBOL_TYPE (sym.symbol);
2407               }
2408             if (type == NULL)
2409               type = rust_lookup_type (varname,
2410                                        pstate->expression_context_block);
2411             if (type == NULL)
2412               error (_("No symbol '%s' in current context"), varname);
2413
2414             if (!want_type
2415                 && TYPE_CODE (type) == TYPE_CODE_STRUCT
2416                 && TYPE_NFIELDS (type) == 0)
2417               {
2418                 /* A unit-like struct.  */
2419                 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2420                 write_exp_elt_type (pstate, type);
2421                 write_exp_elt_longcst (pstate, 0);
2422                 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2423               }
2424             else if (want_type || operation == top)
2425               {
2426                 write_exp_elt_opcode (pstate, OP_TYPE);
2427                 write_exp_elt_type (pstate, type);
2428                 write_exp_elt_opcode (pstate, OP_TYPE);
2429               }
2430             else
2431               error (_("Found type '%s', which can't be "
2432                        "evaluated in this context"),
2433                      varname);
2434           }
2435       }
2436       break;
2437
2438     case OP_AGGREGATE:
2439       {
2440         int length;
2441         rust_set_vector *fields = operation->right.field_inits;
2442         struct type *type;
2443         const char *name;
2444
2445         length = 0;
2446         for (const set_field &init : *fields)
2447           {
2448             if (init.name.ptr != NULL)
2449               {
2450                 write_exp_elt_opcode (pstate, OP_NAME);
2451                 write_exp_string (pstate, init.name);
2452                 write_exp_elt_opcode (pstate, OP_NAME);
2453                 ++length;
2454               }
2455
2456             convert_ast_to_expression (init.init, top);
2457             ++length;
2458
2459             if (init.name.ptr == NULL)
2460               {
2461                 /* This is handled differently from Ada in our
2462                    evaluator.  */
2463                 write_exp_elt_opcode (pstate, OP_OTHERS);
2464               }
2465           }
2466
2467         name = convert_name (operation->left.op);
2468         type = rust_lookup_type (name, pstate->expression_context_block);
2469         if (type == NULL)
2470           error (_("Could not find type '%s'"), operation->left.sval.ptr);
2471
2472         if (TYPE_CODE (type) != TYPE_CODE_STRUCT
2473             || rust_tuple_type_p (type)
2474             || rust_tuple_struct_type_p (type))
2475           error (_("Struct expression applied to non-struct type"));
2476
2477         write_exp_elt_opcode (pstate, OP_AGGREGATE);
2478         write_exp_elt_type (pstate, type);
2479         write_exp_elt_longcst (pstate, length);
2480         write_exp_elt_opcode (pstate, OP_AGGREGATE);
2481       }
2482       break;
2483
2484     case OP_STRING:
2485       {
2486         write_exp_elt_opcode (pstate, OP_STRING);
2487         write_exp_string (pstate, operation->left.sval);
2488         write_exp_elt_opcode (pstate, OP_STRING);
2489       }
2490       break;
2491
2492     case OP_RANGE:
2493       {
2494         enum range_type kind = BOTH_BOUND_DEFAULT;
2495
2496         if (operation->left.op != NULL)
2497           {
2498             convert_ast_to_expression (operation->left.op, top);
2499             kind = HIGH_BOUND_DEFAULT;
2500           }
2501         if (operation->right.op != NULL)
2502           {
2503             convert_ast_to_expression (operation->right.op, top);
2504             if (kind == BOTH_BOUND_DEFAULT)
2505               kind = (operation->inclusive
2506                       ? LOW_BOUND_DEFAULT : LOW_BOUND_DEFAULT_EXCLUSIVE);
2507             else
2508               {
2509                 gdb_assert (kind == HIGH_BOUND_DEFAULT);
2510                 kind = (operation->inclusive
2511                         ? NONE_BOUND_DEFAULT : NONE_BOUND_DEFAULT_EXCLUSIVE);
2512               }
2513           }
2514         else
2515           {
2516             /* Nothing should make an inclusive range without an upper
2517                bound.  */
2518             gdb_assert (!operation->inclusive);
2519           }
2520
2521         write_exp_elt_opcode (pstate, OP_RANGE);
2522         write_exp_elt_longcst (pstate, kind);
2523         write_exp_elt_opcode (pstate, OP_RANGE);
2524       }
2525       break;
2526
2527     default:
2528       gdb_assert_not_reached ("unhandled opcode in convert_ast_to_expression");
2529     }
2530 }
2531
2532 \f
2533
2534 /* The parser as exposed to gdb.  */
2535
2536 int
2537 rust_parse (struct parser_state *state)
2538 {
2539   int result;
2540
2541   /* This sets various globals and also clears them on
2542      destruction.  */
2543   rust_parser parser (state);
2544
2545   result = rustyyparse (&parser);
2546
2547   if (!result || (parse_completion && parser.rust_ast != NULL))
2548     parser.convert_ast_to_expression (parser.rust_ast, parser.rust_ast);
2549
2550   return result;
2551 }
2552
2553 /* The parser error handler.  */
2554
2555 static void
2556 rustyyerror (rust_parser *parser, const char *msg)
2557 {
2558   const char *where = (parser->pstate->prev_lexptr
2559                        ? parser->pstate->prev_lexptr
2560                        : parser->pstate->lexptr);
2561   error (_("%s in expression, near `%s'."), msg, where);
2562 }
2563
2564 \f
2565
2566 #if GDB_SELF_TEST
2567
2568 /* Initialize the lexer for testing.  */
2569
2570 static void
2571 rust_lex_test_init (rust_parser *parser, const char *input)
2572 {
2573   parser->pstate->prev_lexptr = NULL;
2574   parser->pstate->lexptr = input;
2575   parser->paren_depth = 0;
2576 }
2577
2578 /* A test helper that lexes a string, expecting a single token.  It
2579    returns the lexer data for this token.  */
2580
2581 static RUSTSTYPE
2582 rust_lex_test_one (rust_parser *parser, const char *input, int expected)
2583 {
2584   int token;
2585   RUSTSTYPE result;
2586
2587   rust_lex_test_init (parser, input);
2588
2589   token = rustyylex (&result, parser);
2590   SELF_CHECK (token == expected);
2591
2592   if (token)
2593     {
2594       RUSTSTYPE ignore;
2595       token = rustyylex (&ignore, parser);
2596       SELF_CHECK (token == 0);
2597     }
2598
2599   return result;
2600 }
2601
2602 /* Test that INPUT lexes as the integer VALUE.  */
2603
2604 static void
2605 rust_lex_int_test (rust_parser *parser, const char *input, int value, int kind)
2606 {
2607   RUSTSTYPE result = rust_lex_test_one (parser, input, kind);
2608   SELF_CHECK (result.typed_val_int.val == value);
2609 }
2610
2611 /* Test that INPUT throws an exception with text ERR.  */
2612
2613 static void
2614 rust_lex_exception_test (rust_parser *parser, const char *input,
2615                          const char *err)
2616 {
2617   TRY
2618     {
2619       /* The "kind" doesn't matter.  */
2620       rust_lex_test_one (parser, input, DECIMAL_INTEGER);
2621       SELF_CHECK (0);
2622     }
2623   CATCH (except, RETURN_MASK_ERROR)
2624     {
2625       SELF_CHECK (strcmp (except.message, err) == 0);
2626     }
2627   END_CATCH
2628 }
2629
2630 /* Test that INPUT lexes as the identifier, string, or byte-string
2631    VALUE.  KIND holds the expected token kind.  */
2632
2633 static void
2634 rust_lex_stringish_test (rust_parser *parser, const char *input,
2635                          const char *value, int kind)
2636 {
2637   RUSTSTYPE result = rust_lex_test_one (parser, input, kind);
2638   SELF_CHECK (result.sval.length == strlen (value));
2639   SELF_CHECK (strncmp (result.sval.ptr, value, result.sval.length) == 0);
2640 }
2641
2642 /* Helper to test that a string parses as a given token sequence.  */
2643
2644 static void
2645 rust_lex_test_sequence (rust_parser *parser, const char *input, int len,
2646                         const int expected[])
2647 {
2648   int i;
2649
2650   parser->pstate->lexptr = input;
2651   parser->paren_depth = 0;
2652
2653   for (i = 0; i < len; ++i)
2654     {
2655       RUSTSTYPE ignore;
2656       int token = rustyylex (&ignore, parser);
2657
2658       SELF_CHECK (token == expected[i]);
2659     }
2660 }
2661
2662 /* Tests for an integer-parsing corner case.  */
2663
2664 static void
2665 rust_lex_test_trailing_dot (rust_parser *parser)
2666 {
2667   const int expected1[] = { DECIMAL_INTEGER, '.', IDENT, '(', ')', 0 };
2668   const int expected2[] = { INTEGER, '.', IDENT, '(', ')', 0 };
2669   const int expected3[] = { FLOAT, EQEQ, '(', ')', 0 };
2670   const int expected4[] = { DECIMAL_INTEGER, DOTDOT, DECIMAL_INTEGER, 0 };
2671
2672   rust_lex_test_sequence (parser, "23.g()", ARRAY_SIZE (expected1), expected1);
2673   rust_lex_test_sequence (parser, "23_0.g()", ARRAY_SIZE (expected2),
2674                           expected2);
2675   rust_lex_test_sequence (parser, "23.==()", ARRAY_SIZE (expected3),
2676                           expected3);
2677   rust_lex_test_sequence (parser, "23..25", ARRAY_SIZE (expected4), expected4);
2678 }
2679
2680 /* Tests of completion.  */
2681
2682 static void
2683 rust_lex_test_completion (rust_parser *parser)
2684 {
2685   const int expected[] = { IDENT, '.', COMPLETE, 0 };
2686
2687   parse_completion = 1;
2688
2689   rust_lex_test_sequence (parser, "something.wha", ARRAY_SIZE (expected),
2690                           expected);
2691   rust_lex_test_sequence (parser, "something.", ARRAY_SIZE (expected),
2692                           expected);
2693
2694   parse_completion = 0;
2695 }
2696
2697 /* Test pushback.  */
2698
2699 static void
2700 rust_lex_test_push_back (rust_parser *parser)
2701 {
2702   int token;
2703   RUSTSTYPE lval;
2704
2705   rust_lex_test_init (parser, ">>=");
2706
2707   token = rustyylex (&lval, parser);
2708   SELF_CHECK (token == COMPOUND_ASSIGN);
2709   SELF_CHECK (lval.opcode == BINOP_RSH);
2710
2711   parser->push_back ('=');
2712
2713   token = rustyylex (&lval, parser);
2714   SELF_CHECK (token == '=');
2715
2716   token = rustyylex (&lval, parser);
2717   SELF_CHECK (token == 0);
2718 }
2719
2720 /* Unit test the lexer.  */
2721
2722 static void
2723 rust_lex_tests (void)
2724 {
2725   int i;
2726
2727   // Set up dummy "parser", so that rust_type works.
2728   struct parser_state ps (&rust_language_defn, target_gdbarch (),
2729                           nullptr, 0, 0, nullptr);
2730   rust_parser parser (&ps);
2731
2732   rust_lex_test_one (&parser, "", 0);
2733   rust_lex_test_one (&parser, "    \t  \n \r  ", 0);
2734   rust_lex_test_one (&parser, "thread 23", 0);
2735   rust_lex_test_one (&parser, "task 23", 0);
2736   rust_lex_test_one (&parser, "th 104", 0);
2737   rust_lex_test_one (&parser, "ta 97", 0);
2738
2739   rust_lex_int_test (&parser, "'z'", 'z', INTEGER);
2740   rust_lex_int_test (&parser, "'\\xff'", 0xff, INTEGER);
2741   rust_lex_int_test (&parser, "'\\u{1016f}'", 0x1016f, INTEGER);
2742   rust_lex_int_test (&parser, "b'z'", 'z', INTEGER);
2743   rust_lex_int_test (&parser, "b'\\xfe'", 0xfe, INTEGER);
2744   rust_lex_int_test (&parser, "b'\\xFE'", 0xfe, INTEGER);
2745   rust_lex_int_test (&parser, "b'\\xfE'", 0xfe, INTEGER);
2746
2747   /* Test all escapes in both modes.  */
2748   rust_lex_int_test (&parser, "'\\n'", '\n', INTEGER);
2749   rust_lex_int_test (&parser, "'\\r'", '\r', INTEGER);
2750   rust_lex_int_test (&parser, "'\\t'", '\t', INTEGER);
2751   rust_lex_int_test (&parser, "'\\\\'", '\\', INTEGER);
2752   rust_lex_int_test (&parser, "'\\0'", '\0', INTEGER);
2753   rust_lex_int_test (&parser, "'\\''", '\'', INTEGER);
2754   rust_lex_int_test (&parser, "'\\\"'", '"', INTEGER);
2755
2756   rust_lex_int_test (&parser, "b'\\n'", '\n', INTEGER);
2757   rust_lex_int_test (&parser, "b'\\r'", '\r', INTEGER);
2758   rust_lex_int_test (&parser, "b'\\t'", '\t', INTEGER);
2759   rust_lex_int_test (&parser, "b'\\\\'", '\\', INTEGER);
2760   rust_lex_int_test (&parser, "b'\\0'", '\0', INTEGER);
2761   rust_lex_int_test (&parser, "b'\\''", '\'', INTEGER);
2762   rust_lex_int_test (&parser, "b'\\\"'", '"', INTEGER);
2763
2764   rust_lex_exception_test (&parser, "'z", "Unterminated character literal");
2765   rust_lex_exception_test (&parser, "b'\\x0'", "Not enough hex digits seen");
2766   rust_lex_exception_test (&parser, "b'\\u{0}'",
2767                            "Unicode escape in byte literal");
2768   rust_lex_exception_test (&parser, "'\\x0'", "Not enough hex digits seen");
2769   rust_lex_exception_test (&parser, "'\\u0'", "Missing '{' in Unicode escape");
2770   rust_lex_exception_test (&parser, "'\\u{0", "Missing '}' in Unicode escape");
2771   rust_lex_exception_test (&parser, "'\\u{0000007}", "Overlong hex escape");
2772   rust_lex_exception_test (&parser, "'\\u{}", "Not enough hex digits seen");
2773   rust_lex_exception_test (&parser, "'\\Q'", "Invalid escape \\Q in literal");
2774   rust_lex_exception_test (&parser, "b'\\Q'", "Invalid escape \\Q in literal");
2775
2776   rust_lex_int_test (&parser, "23", 23, DECIMAL_INTEGER);
2777   rust_lex_int_test (&parser, "2_344__29", 234429, INTEGER);
2778   rust_lex_int_test (&parser, "0x1f", 0x1f, INTEGER);
2779   rust_lex_int_test (&parser, "23usize", 23, INTEGER);
2780   rust_lex_int_test (&parser, "23i32", 23, INTEGER);
2781   rust_lex_int_test (&parser, "0x1_f", 0x1f, INTEGER);
2782   rust_lex_int_test (&parser, "0b1_101011__", 0x6b, INTEGER);
2783   rust_lex_int_test (&parser, "0o001177i64", 639, INTEGER);
2784
2785   rust_lex_test_trailing_dot (&parser);
2786
2787   rust_lex_test_one (&parser, "23.", FLOAT);
2788   rust_lex_test_one (&parser, "23.99f32", FLOAT);
2789   rust_lex_test_one (&parser, "23e7", FLOAT);
2790   rust_lex_test_one (&parser, "23E-7", FLOAT);
2791   rust_lex_test_one (&parser, "23e+7", FLOAT);
2792   rust_lex_test_one (&parser, "23.99e+7f64", FLOAT);
2793   rust_lex_test_one (&parser, "23.82f32", FLOAT);
2794
2795   rust_lex_stringish_test (&parser, "hibob", "hibob", IDENT);
2796   rust_lex_stringish_test (&parser, "hibob__93", "hibob__93", IDENT);
2797   rust_lex_stringish_test (&parser, "thread", "thread", IDENT);
2798
2799   rust_lex_stringish_test (&parser, "\"string\"", "string", STRING);
2800   rust_lex_stringish_test (&parser, "\"str\\ting\"", "str\ting", STRING);
2801   rust_lex_stringish_test (&parser, "\"str\\\"ing\"", "str\"ing", STRING);
2802   rust_lex_stringish_test (&parser, "r\"str\\ing\"", "str\\ing", STRING);
2803   rust_lex_stringish_test (&parser, "r#\"str\\ting\"#", "str\\ting", STRING);
2804   rust_lex_stringish_test (&parser, "r###\"str\\\"ing\"###", "str\\\"ing",
2805                            STRING);
2806
2807   rust_lex_stringish_test (&parser, "b\"string\"", "string", BYTESTRING);
2808   rust_lex_stringish_test (&parser, "b\"\x73tring\"", "string", BYTESTRING);
2809   rust_lex_stringish_test (&parser, "b\"str\\\"ing\"", "str\"ing", BYTESTRING);
2810   rust_lex_stringish_test (&parser, "br####\"\\x73tring\"####", "\\x73tring",
2811                            BYTESTRING);
2812
2813   for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
2814     rust_lex_test_one (&parser, identifier_tokens[i].name,
2815                        identifier_tokens[i].value);
2816
2817   for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
2818     rust_lex_test_one (&parser, operator_tokens[i].name,
2819                        operator_tokens[i].value);
2820
2821   rust_lex_test_completion (&parser);
2822   rust_lex_test_push_back (&parser);
2823 }
2824
2825 #endif /* GDB_SELF_TEST */
2826
2827 void
2828 _initialize_rust_exp (void)
2829 {
2830   int code = regcomp (&number_regex, number_regex_text, REG_EXTENDED);
2831   /* If the regular expression was incorrect, it was a programming
2832      error.  */
2833   gdb_assert (code == 0);
2834
2835 #if GDB_SELF_TEST
2836   selftests::register_test ("rust-lex", rust_lex_tests);
2837 #endif
2838 }