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