1 /* Bison parser for Rust expressions, for GDB.
2 Copyright (C) 2016-2019 Free Software Foundation, Inc.
4 This file is part of GDB.
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.
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.
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/>. */
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. */
24 %lex-param {struct rust_parser *parser}
25 %parse-param {struct rust_parser *parser}
27 /* Removing the last conflict seems difficult. */
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"
43 #include "common/vec.h"
45 #define GDB_YY_REMAP_PREFIX rust
48 #define RUSTSTYPE YYSTYPE
51 typedef std::vector<const struct rust_op *> rust_op_vector;
53 /* A typed integer constant. */
61 /* A typed floating point constant. */
63 struct typed_val_float
69 /* An identifier and an expression. This is used to represent one
70 element of a struct initializer. */
75 const struct rust_op *init;
78 typedef std::vector<set_field> rust_set_vector;
84 /* A typed integer constant. */
85 struct typed_val_int typed_val_int;
87 /* A typed floating point constant. */
88 struct typed_val_float typed_val_float;
90 /* An identifier or string. */
93 /* A token representing an opcode, like "==". */
94 enum exp_opcode opcode;
96 /* A list of expressions; for example, the arguments to a function
98 rust_op_vector *params;
100 /* A list of field initializers. */
101 rust_set_vector *field_inits;
103 /* A single field initializer. */
104 struct set_field one_field_init;
107 const struct rust_op *op;
109 /* A plain integer, for example used to count the number of
110 "super::" prefixes on a path. */
117 static int rustyylex (YYSTYPE *, rust_parser *);
118 static void rustyyerror (rust_parser *parser, const char *msg);
120 static void rust_push_back (char c);
121 static struct stoken make_stoken (const char *);
122 static struct block_symbol rust_lookup_symbol (const char *name,
123 const struct block *block,
124 const domain_enum domain);
126 /* A regular expression for matching Rust numbers. This is split up
127 since it is very long and this gives us a way to comment the
130 static const char *number_regex_text =
131 /* subexpression 1: allows use of alternation, otherwise uninteresting */
133 /* First comes floating point. */
134 /* Recognize number after the decimal point, with optional
135 exponent and optional type suffix.
136 subexpression 2: allows "?", otherwise uninteresting
137 subexpression 3: if present, type suffix
139 "[0-9][0-9_]*\\.[0-9][0-9_]*([eE][-+]?[0-9][0-9_]*)?(f32|f64)?"
140 #define FLOAT_TYPE1 3
142 /* Recognize exponent without decimal point, with optional type
144 subexpression 4: if present, type suffix
146 #define FLOAT_TYPE2 4
147 "[0-9][0-9_]*[eE][-+]?[0-9][0-9_]*(f32|f64)?"
149 /* "23." is a valid floating point number, but "23.e5" and
150 "23.f32" are not. So, handle the trailing-. case
154 /* Finally come integers.
155 subexpression 5: text of integer
156 subexpression 6: if present, type suffix
157 subexpression 7: allows use of alternation, otherwise uninteresting
161 "(0x[a-fA-F0-9_]+|0o[0-7_]+|0b[01_]+|[0-9][0-9_]*)"
162 "([iu](size|8|16|32|64))?"
164 /* The number of subexpressions to allocate space for, including the
165 "0th" whole match subexpression. */
166 #define NUM_SUBEXPRESSIONS 8
168 /* The compiled number-matching regex. */
170 static regex_t number_regex;
172 /* An instance of this is created before parsing, and destroyed when
173 parsing is finished. */
177 rust_parser (struct parser_state *state)
178 : rust_ast (nullptr),
187 /* Create a new rust_set_vector. The storage for the new vector is
188 managed by this class. */
189 rust_set_vector *new_set_vector ()
191 rust_set_vector *result = new rust_set_vector;
192 set_vectors.push_back (std::unique_ptr<rust_set_vector> (result));
196 /* Create a new rust_ops_vector. The storage for the new vector is
197 managed by this class. */
198 rust_op_vector *new_op_vector ()
200 rust_op_vector *result = new rust_op_vector;
201 op_vectors.push_back (std::unique_ptr<rust_op_vector> (result));
205 /* Return the parser's language. */
206 const struct language_defn *language () const
208 return parse_language (pstate);
211 /* Return the parser's gdbarch. */
212 struct gdbarch *arch () const
214 return parse_gdbarch (pstate);
217 /* A helper to look up a Rust type, or fail. This only works for
218 types defined by rust_language_arch_info. */
220 struct type *get_type (const char *name)
224 type = language_lookup_primitive_type (language (), arch (), name);
226 error (_("Could not find Rust type %s"), name);
230 const char *copy_name (const char *name, int len);
231 struct stoken concat3 (const char *s1, const char *s2, const char *s3);
232 const struct rust_op *crate_name (const struct rust_op *name);
233 const struct rust_op *super_name (const struct rust_op *ident,
234 unsigned int n_supers);
236 int lex_character (YYSTYPE *lvalp);
237 int lex_number (YYSTYPE *lvalp);
238 int lex_string (YYSTYPE *lvalp);
239 int lex_identifier (YYSTYPE *lvalp);
241 struct type *rust_lookup_type (const char *name, const struct block *block);
242 std::vector<struct type *> convert_params_to_types (rust_op_vector *params);
243 struct type *convert_ast_to_type (const struct rust_op *operation);
244 const char *convert_name (const struct rust_op *operation);
245 void convert_params_to_expression (rust_op_vector *params,
246 const struct rust_op *top);
247 void convert_ast_to_expression (const struct rust_op *operation,
248 const struct rust_op *top,
249 bool want_type = false);
251 struct rust_op *ast_basic_type (enum type_code typecode);
252 const struct rust_op *ast_operation (enum exp_opcode opcode,
253 const struct rust_op *left,
254 const struct rust_op *right);
255 const struct rust_op *ast_compound_assignment
256 (enum exp_opcode opcode, const struct rust_op *left,
257 const struct rust_op *rust_op);
258 const struct rust_op *ast_literal (struct typed_val_int val);
259 const struct rust_op *ast_dliteral (struct typed_val_float val);
260 const struct rust_op *ast_structop (const struct rust_op *left,
263 const struct rust_op *ast_structop_anonymous
264 (const struct rust_op *left, struct typed_val_int number);
265 const struct rust_op *ast_unary (enum exp_opcode opcode,
266 const struct rust_op *expr);
267 const struct rust_op *ast_cast (const struct rust_op *expr,
268 const struct rust_op *type);
269 const struct rust_op *ast_call_ish (enum exp_opcode opcode,
270 const struct rust_op *expr,
271 rust_op_vector *params);
272 const struct rust_op *ast_path (struct stoken name,
273 rust_op_vector *params);
274 const struct rust_op *ast_string (struct stoken str);
275 const struct rust_op *ast_struct (const struct rust_op *name,
276 rust_set_vector *fields);
277 const struct rust_op *ast_range (const struct rust_op *lhs,
278 const struct rust_op *rhs,
280 const struct rust_op *ast_array_type (const struct rust_op *lhs,
281 struct typed_val_int val);
282 const struct rust_op *ast_slice_type (const struct rust_op *type);
283 const struct rust_op *ast_reference_type (const struct rust_op *type);
284 const struct rust_op *ast_pointer_type (const struct rust_op *type,
286 const struct rust_op *ast_function_type (const struct rust_op *result,
287 rust_op_vector *params);
288 const struct rust_op *ast_tuple_type (rust_op_vector *params);
291 /* A pointer to this is installed globally. */
292 auto_obstack obstack;
294 /* Result of parsing. Points into obstack. */
295 const struct rust_op *rust_ast;
297 /* This keeps track of the various vectors we allocate. */
298 std::vector<std::unique_ptr<rust_set_vector>> set_vectors;
299 std::vector<std::unique_ptr<rust_op_vector>> op_vectors;
301 /* The parser state gdb gave us. */
302 struct parser_state *pstate;
305 /* Rust AST operations. We build a tree of these; then lower them to
306 gdb expressions when parsing has completed. */
311 enum exp_opcode opcode;
312 /* If OPCODE is OP_TYPE, then this holds information about what type
313 is described by this node. */
314 enum type_code typecode;
315 /* Indicates whether OPCODE actually represents a compound
316 assignment. For example, if OPCODE is GTGT and this is false,
317 then this rust_op represents an ordinary ">>"; but if this is
318 true, then this rust_op represents ">>=". Unused in other
320 unsigned int compound_assignment : 1;
321 /* Only used by a field expression; if set, indicates that the field
322 name occurred at the end of the expression and is eligible for
324 unsigned int completing : 1;
325 /* For OP_RANGE, indicates whether the range is inclusive or
327 unsigned int inclusive : 1;
328 /* Operands of expression. Which one is used and how depends on the
329 particular opcode. */
338 %token <sval> COMPLETE
339 %token <typed_val_int> INTEGER
340 %token <typed_val_int> DECIMAL_INTEGER
342 %token <sval> BYTESTRING
343 %token <typed_val_float> FLOAT
344 %token <opcode> COMPOUND_ASSIGN
346 /* Keyword tokens. */
347 %token <voidval> KW_AS
348 %token <voidval> KW_IF
349 %token <voidval> KW_TRUE
350 %token <voidval> KW_FALSE
351 %token <voidval> KW_SUPER
352 %token <voidval> KW_SELF
353 %token <voidval> KW_MUT
354 %token <voidval> KW_EXTERN
355 %token <voidval> KW_CONST
356 %token <voidval> KW_FN
357 %token <voidval> KW_SIZEOF
359 /* Operator tokens. */
360 %token <voidval> DOTDOT
361 %token <voidval> DOTDOTEQ
362 %token <voidval> OROR
363 %token <voidval> ANDAND
364 %token <voidval> EQEQ
365 %token <voidval> NOTEQ
366 %token <voidval> LTEQ
367 %token <voidval> GTEQ
368 %token <voidval> LSH RSH
369 %token <voidval> COLONCOLON
370 %token <voidval> ARROW
373 %type <op> path_for_expr
374 %type <op> identifier_path_for_expr
375 %type <op> path_for_type
376 %type <op> identifier_path_for_type
377 %type <op> just_identifiers_for_type
379 %type <params> maybe_type_list
380 %type <params> type_list
382 %type <depth> super_path
386 %type <op> field_expr
389 %type <op> binop_expr
390 %type <op> binop_expr_expr
391 %type <op> type_cast_expr
392 %type <op> assignment_expr
393 %type <op> compound_assignment_expr
394 %type <op> paren_expr
397 %type <op> tuple_expr
399 %type <op> struct_expr
400 %type <op> array_expr
401 %type <op> range_expr
403 %type <params> expr_list
404 %type <params> maybe_expr_list
405 %type <params> paren_expr_list
407 %type <field_inits> struct_expr_list
408 %type <one_field_init> struct_expr_tail
411 %nonassoc DOTDOT DOTDOTEQ
412 %right '=' COMPOUND_ASSIGN
415 %nonassoc EQEQ NOTEQ '<' '>' LTEQ GTEQ
423 /* These could be %precedence in Bison, but that isn't a yacc
434 /* If we are completing and see a valid parse,
435 rust_ast will already have been set. */
436 if (parser->rust_ast == NULL)
437 parser->rust_ast = $1;
441 /* Note that the Rust grammar includes a method_call_expr, but we
442 handle this differently, to avoid a shift/reduce conflict with
454 | unop_expr /* Must precede call_expr because of ambiguity with
462 '(' expr ',' maybe_expr_list ')'
465 error (_("Tuple expressions not supported yet"));
472 struct typed_val_int val;
475 = (language_lookup_primitive_type
476 (parser->language (), parser->arch (),
479 $$ = parser->ast_literal (val);
483 /* To avoid a shift/reduce conflict with call_expr, we don't handle
484 tuple struct expressions here, but instead when examining the
487 path_for_expr '{' struct_expr_list '}'
488 { $$ = parser->ast_struct ($1, $3); }
515 sf.init = parser->ast_path ($1, NULL);
523 $$ = parser->new_set_vector ();
527 rust_set_vector *result = parser->new_set_vector ();
528 result->push_back ($1);
531 | IDENT ':' expr ',' struct_expr_list
540 | IDENT ',' struct_expr_list
545 sf.init = parser->ast_path ($1, NULL);
552 '[' KW_MUT expr_list ']'
553 { $$ = parser->ast_call_ish (OP_ARRAY, NULL, $3); }
555 { $$ = parser->ast_call_ish (OP_ARRAY, NULL, $2); }
556 | '[' KW_MUT expr ';' expr ']'
557 { $$ = parser->ast_operation (OP_RUST_ARRAY, $3, $5); }
558 | '[' expr ';' expr ']'
559 { $$ = parser->ast_operation (OP_RUST_ARRAY, $2, $4); }
564 { $$ = parser->ast_range ($1, NULL, false); }
566 { $$ = parser->ast_range ($1, $3, false); }
568 { $$ = parser->ast_range ($1, $3, true); }
570 { $$ = parser->ast_range (NULL, $2, false); }
572 { $$ = parser->ast_range (NULL, $2, true); }
574 { $$ = parser->ast_range (NULL, NULL, false); }
579 { $$ = parser->ast_literal ($1); }
581 { $$ = parser->ast_literal ($1); }
583 { $$ = parser->ast_dliteral ($1); }
586 struct set_field field;
587 struct typed_val_int val;
590 rust_set_vector *fields = parser->new_set_vector ();
592 /* Wrap the raw string in the &str struct. */
593 field.name.ptr = "data_ptr";
594 field.name.length = strlen (field.name.ptr);
595 field.init = parser->ast_unary (UNOP_ADDR,
596 parser->ast_string ($1));
597 fields->push_back (field);
599 val.type = parser->get_type ("usize");
602 field.name.ptr = "length";
603 field.name.length = strlen (field.name.ptr);
604 field.init = parser->ast_literal (val);
605 fields->push_back (field);
608 token.length = strlen (token.ptr);
609 $$ = parser->ast_struct (parser->ast_path (token, NULL),
613 { $$ = parser->ast_string ($1); }
616 struct typed_val_int val;
618 val.type = language_bool_type (parser->language (),
621 $$ = parser->ast_literal (val);
625 struct typed_val_int val;
627 val.type = language_bool_type (parser->language (),
630 $$ = parser->ast_literal (val);
636 { $$ = parser->ast_structop ($1, $3.ptr, 0); }
639 $$ = parser->ast_structop ($1, $3.ptr, 1);
640 parser->rust_ast = $$;
642 | expr '.' DECIMAL_INTEGER
643 { $$ = parser->ast_structop_anonymous ($1, $3); }
648 { $$ = parser->ast_operation (BINOP_SUBSCRIPT, $1, $3); }
653 { $$ = parser->ast_unary (UNOP_PLUS, $2); }
655 | '-' expr %prec UNARY
656 { $$ = parser->ast_unary (UNOP_NEG, $2); }
658 | '!' expr %prec UNARY
660 /* Note that we provide a Rust-specific evaluator
661 override for UNOP_COMPLEMENT, so it can do the
662 right thing for both bool and integral
664 $$ = parser->ast_unary (UNOP_COMPLEMENT, $2);
667 | '*' expr %prec UNARY
668 { $$ = parser->ast_unary (UNOP_IND, $2); }
670 | '&' expr %prec UNARY
671 { $$ = parser->ast_unary (UNOP_ADDR, $2); }
673 | '&' KW_MUT expr %prec UNARY
674 { $$ = parser->ast_unary (UNOP_ADDR, $3); }
675 | KW_SIZEOF '(' expr ')' %prec UNARY
676 { $$ = parser->ast_unary (UNOP_SIZEOF, $3); }
683 | compound_assignment_expr
688 { $$ = parser->ast_operation (BINOP_MUL, $1, $3); }
691 { $$ = parser->ast_operation (BINOP_REPEAT, $1, $3); }
694 { $$ = parser->ast_operation (BINOP_DIV, $1, $3); }
697 { $$ = parser->ast_operation (BINOP_REM, $1, $3); }
700 { $$ = parser->ast_operation (BINOP_LESS, $1, $3); }
703 { $$ = parser->ast_operation (BINOP_GTR, $1, $3); }
706 { $$ = parser->ast_operation (BINOP_BITWISE_AND, $1, $3); }
709 { $$ = parser->ast_operation (BINOP_BITWISE_IOR, $1, $3); }
712 { $$ = parser->ast_operation (BINOP_BITWISE_XOR, $1, $3); }
715 { $$ = parser->ast_operation (BINOP_ADD, $1, $3); }
718 { $$ = parser->ast_operation (BINOP_SUB, $1, $3); }
721 { $$ = parser->ast_operation (BINOP_LOGICAL_OR, $1, $3); }
724 { $$ = parser->ast_operation (BINOP_LOGICAL_AND, $1, $3); }
727 { $$ = parser->ast_operation (BINOP_EQUAL, $1, $3); }
730 { $$ = parser->ast_operation (BINOP_NOTEQUAL, $1, $3); }
733 { $$ = parser->ast_operation (BINOP_LEQ, $1, $3); }
736 { $$ = parser->ast_operation (BINOP_GEQ, $1, $3); }
739 { $$ = parser->ast_operation (BINOP_LSH, $1, $3); }
742 { $$ = parser->ast_operation (BINOP_RSH, $1, $3); }
747 { $$ = parser->ast_cast ($1, $3); }
752 { $$ = parser->ast_operation (BINOP_ASSIGN, $1, $3); }
755 compound_assignment_expr:
756 expr COMPOUND_ASSIGN expr
757 { $$ = parser->ast_compound_assignment ($2, $1, $3); }
769 $$ = parser->new_op_vector ();
782 /* The result can't be NULL. */
783 $$ = parser->new_op_vector ();
790 '(' maybe_expr_list ')'
796 { $$ = parser->ast_call_ish (OP_FUNCALL, $1, $2); }
807 | super_path KW_SUPER COLONCOLON
815 { $$ = parser->ast_path ($1, NULL); }
817 { $$ = parser->ast_path (make_stoken ("self"), NULL); }
821 identifier_path_for_expr
822 | KW_SELF COLONCOLON identifier_path_for_expr
823 { $$ = parser->super_name ($3, 0); }
824 | maybe_self_path super_path identifier_path_for_expr
825 { $$ = parser->super_name ($3, $2); }
826 | COLONCOLON identifier_path_for_expr
827 { $$ = parser->crate_name ($2); }
828 | KW_EXTERN identifier_path_for_expr
830 /* This is a gdb extension to make it possible to
831 refer to items in other crates. It just bypasses
832 adding the current crate to the front of the
834 $$ = parser->ast_path (parser->concat3 ("::",
841 identifier_path_for_expr:
843 { $$ = parser->ast_path ($1, NULL); }
844 | identifier_path_for_expr COLONCOLON IDENT
846 $$ = parser->ast_path (parser->concat3 ($1->left.sval.ptr,
850 | identifier_path_for_expr COLONCOLON '<' type_list '>'
851 { $$ = parser->ast_path ($1->left.sval, $4); }
852 | identifier_path_for_expr COLONCOLON '<' type_list RSH
854 $$ = parser->ast_path ($1->left.sval, $4);
855 rust_push_back ('>');
860 identifier_path_for_type
861 | KW_SELF COLONCOLON identifier_path_for_type
862 { $$ = parser->super_name ($3, 0); }
863 | maybe_self_path super_path identifier_path_for_type
864 { $$ = parser->super_name ($3, $2); }
865 | COLONCOLON identifier_path_for_type
866 { $$ = parser->crate_name ($2); }
867 | KW_EXTERN identifier_path_for_type
869 /* This is a gdb extension to make it possible to
870 refer to items in other crates. It just bypasses
871 adding the current crate to the front of the
873 $$ = parser->ast_path (parser->concat3 ("::",
880 just_identifiers_for_type:
882 { $$ = parser->ast_path ($1, NULL); }
883 | just_identifiers_for_type COLONCOLON IDENT
885 $$ = parser->ast_path (parser->concat3 ($1->left.sval.ptr,
891 identifier_path_for_type:
892 just_identifiers_for_type
893 | just_identifiers_for_type '<' type_list '>'
894 { $$ = parser->ast_path ($1->left.sval, $3); }
895 | just_identifiers_for_type '<' type_list RSH
897 $$ = parser->ast_path ($1->left.sval, $3);
898 rust_push_back ('>');
904 | '[' type ';' INTEGER ']'
905 { $$ = parser->ast_array_type ($2, $4); }
906 | '[' type ';' DECIMAL_INTEGER ']'
907 { $$ = parser->ast_array_type ($2, $4); }
909 { $$ = parser->ast_slice_type ($3); }
911 { $$ = parser->ast_reference_type ($2); }
913 { $$ = parser->ast_pointer_type ($3, 1); }
915 { $$ = parser->ast_pointer_type ($3, 0); }
916 | KW_FN '(' maybe_type_list ')' ARROW type
917 { $$ = parser->ast_function_type ($6, $3); }
918 | '(' maybe_type_list ')'
919 { $$ = parser->ast_tuple_type ($2); }
932 rust_op_vector *result = parser->new_op_vector ();
933 result->push_back ($1);
945 /* A struct of this type is used to describe a token. */
951 enum exp_opcode opcode;
954 /* Identifier tokens. */
956 static const struct token_info identifier_tokens[] =
958 { "as", KW_AS, OP_NULL },
959 { "false", KW_FALSE, OP_NULL },
960 { "if", 0, OP_NULL },
961 { "mut", KW_MUT, OP_NULL },
962 { "const", KW_CONST, OP_NULL },
963 { "self", KW_SELF, OP_NULL },
964 { "super", KW_SUPER, OP_NULL },
965 { "true", KW_TRUE, OP_NULL },
966 { "extern", KW_EXTERN, OP_NULL },
967 { "fn", KW_FN, OP_NULL },
968 { "sizeof", KW_SIZEOF, OP_NULL },
971 /* Operator tokens, sorted longest first. */
973 static const struct token_info operator_tokens[] =
975 { ">>=", COMPOUND_ASSIGN, BINOP_RSH },
976 { "<<=", COMPOUND_ASSIGN, BINOP_LSH },
978 { "<<", LSH, OP_NULL },
979 { ">>", RSH, OP_NULL },
980 { "&&", ANDAND, OP_NULL },
981 { "||", OROR, OP_NULL },
982 { "==", EQEQ, OP_NULL },
983 { "!=", NOTEQ, OP_NULL },
984 { "<=", LTEQ, OP_NULL },
985 { ">=", GTEQ, OP_NULL },
986 { "+=", COMPOUND_ASSIGN, BINOP_ADD },
987 { "-=", COMPOUND_ASSIGN, BINOP_SUB },
988 { "*=", COMPOUND_ASSIGN, BINOP_MUL },
989 { "/=", COMPOUND_ASSIGN, BINOP_DIV },
990 { "%=", COMPOUND_ASSIGN, BINOP_REM },
991 { "&=", COMPOUND_ASSIGN, BINOP_BITWISE_AND },
992 { "|=", COMPOUND_ASSIGN, BINOP_BITWISE_IOR },
993 { "^=", COMPOUND_ASSIGN, BINOP_BITWISE_XOR },
994 { "..=", DOTDOTEQ, OP_NULL },
996 { "::", COLONCOLON, OP_NULL },
997 { "..", DOTDOT, OP_NULL },
998 { "->", ARROW, OP_NULL }
1001 /* Helper function to copy to the name obstack. */
1004 rust_parser::copy_name (const char *name, int len)
1006 return (const char *) obstack_copy0 (&obstack, name, len);
1009 /* Helper function to make an stoken from a C string. */
1011 static struct stoken
1012 make_stoken (const char *p)
1014 struct stoken result;
1017 result.length = strlen (result.ptr);
1021 /* Helper function to concatenate three strings on the name
1025 rust_parser::concat3 (const char *s1, const char *s2, const char *s3)
1027 return make_stoken (obconcat (&obstack, s1, s2, s3, (char *) NULL));
1030 /* Return an AST node referring to NAME, but relative to the crate's
1033 const struct rust_op *
1034 rust_parser::crate_name (const struct rust_op *name)
1036 std::string crate = rust_crate_for_block (expression_context_block);
1037 struct stoken result;
1039 gdb_assert (name->opcode == OP_VAR_VALUE);
1042 error (_("Could not find crate for current location"));
1043 result = make_stoken (obconcat (&obstack, "::", crate.c_str (), "::",
1044 name->left.sval.ptr, (char *) NULL));
1046 return ast_path (result, name->right.params);
1049 /* Create an AST node referring to a "super::" qualified name. IDENT
1050 is the base name and N_SUPERS is how many "super::"s were
1051 provided. N_SUPERS can be zero. */
1053 const struct rust_op *
1054 rust_parser::super_name (const struct rust_op *ident, unsigned int n_supers)
1056 const char *scope = block_scope (expression_context_block);
1059 gdb_assert (ident->opcode == OP_VAR_VALUE);
1061 if (scope[0] == '\0')
1062 error (_("Couldn't find namespace scope for self::"));
1067 std::vector<int> offsets;
1068 unsigned int current_len;
1070 current_len = cp_find_first_component (scope);
1071 while (scope[current_len] != '\0')
1073 offsets.push_back (current_len);
1074 gdb_assert (scope[current_len] == ':');
1077 current_len += cp_find_first_component (scope
1081 len = offsets.size ();
1082 if (n_supers >= len)
1083 error (_("Too many super:: uses from '%s'"), scope);
1085 offset = offsets[len - n_supers];
1088 offset = strlen (scope);
1090 obstack_grow (&obstack, "::", 2);
1091 obstack_grow (&obstack, scope, offset);
1092 obstack_grow (&obstack, "::", 2);
1093 obstack_grow0 (&obstack, ident->left.sval.ptr, ident->left.sval.length);
1095 return ast_path (make_stoken ((const char *) obstack_finish (&obstack)),
1096 ident->right.params);
1099 /* A helper that updates the innermost block as appropriate. */
1102 update_innermost_block (struct block_symbol sym)
1104 if (symbol_read_needs_frame (sym.symbol))
1105 innermost_block.update (sym);
1108 /* Lex a hex number with at least MIN digits and at most MAX
1112 lex_hex (int min, int max)
1114 uint32_t result = 0;
1116 /* We only want to stop at MAX if we're lexing a byte escape. */
1117 int check_max = min == max;
1119 while ((check_max ? len <= max : 1)
1120 && ((lexptr[0] >= 'a' && lexptr[0] <= 'f')
1121 || (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1122 || (lexptr[0] >= '0' && lexptr[0] <= '9')))
1125 if (lexptr[0] >= 'a' && lexptr[0] <= 'f')
1126 result = result + 10 + lexptr[0] - 'a';
1127 else if (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1128 result = result + 10 + lexptr[0] - 'A';
1130 result = result + lexptr[0] - '0';
1136 error (_("Not enough hex digits seen"));
1139 gdb_assert (min != max);
1140 error (_("Overlong hex escape"));
1146 /* Lex an escape. IS_BYTE is true if we're lexing a byte escape;
1147 otherwise we're lexing a character escape. */
1150 lex_escape (int is_byte)
1154 gdb_assert (lexptr[0] == '\\');
1160 result = lex_hex (2, 2);
1165 error (_("Unicode escape in byte literal"));
1167 if (lexptr[0] != '{')
1168 error (_("Missing '{' in Unicode escape"));
1170 result = lex_hex (1, 6);
1171 /* Could do range checks here. */
1172 if (lexptr[0] != '}')
1173 error (_("Missing '}' in Unicode escape"));
1207 error (_("Invalid escape \\%c in literal"), lexptr[0]);
1213 /* Lex a character constant. */
1216 rust_parser::lex_character (YYSTYPE *lvalp)
1221 if (lexptr[0] == 'b')
1226 gdb_assert (lexptr[0] == '\'');
1228 /* This should handle UTF-8 here. */
1229 if (lexptr[0] == '\\')
1230 value = lex_escape (is_byte);
1233 value = lexptr[0] & 0xff;
1237 if (lexptr[0] != '\'')
1238 error (_("Unterminated character literal"));
1241 lvalp->typed_val_int.val = value;
1242 lvalp->typed_val_int.type = get_type (is_byte ? "u8" : "char");
1247 /* Return the offset of the double quote if STR looks like the start
1248 of a raw string, or 0 if STR does not start a raw string. */
1251 starts_raw_string (const char *str)
1253 const char *save = str;
1258 while (str[0] == '#')
1265 /* Return true if STR looks like the end of a raw string that had N
1266 hashes at the start. */
1269 ends_raw_string (const char *str, int n)
1273 gdb_assert (str[0] == '"');
1274 for (i = 0; i < n; ++i)
1275 if (str[i + 1] != '#')
1280 /* Lex a string constant. */
1283 rust_parser::lex_string (YYSTYPE *lvalp)
1285 int is_byte = lexptr[0] == 'b';
1290 raw_length = starts_raw_string (lexptr);
1291 lexptr += raw_length;
1292 gdb_assert (lexptr[0] == '"');
1301 if (lexptr[0] == '"' && ends_raw_string (lexptr, raw_length - 1))
1303 /* Exit with lexptr pointing after the final "#". */
1304 lexptr += raw_length;
1307 else if (lexptr[0] == '\0')
1308 error (_("Unexpected EOF in string"));
1310 value = lexptr[0] & 0xff;
1311 if (is_byte && value > 127)
1312 error (_("Non-ASCII value in raw byte string"));
1313 obstack_1grow (&obstack, value);
1317 else if (lexptr[0] == '"')
1319 /* Make sure to skip the quote. */
1323 else if (lexptr[0] == '\\')
1325 value = lex_escape (is_byte);
1328 obstack_1grow (&obstack, value);
1330 convert_between_encodings ("UTF-32", "UTF-8", (gdb_byte *) &value,
1331 sizeof (value), sizeof (value),
1332 &obstack, translit_none);
1334 else if (lexptr[0] == '\0')
1335 error (_("Unexpected EOF in string"));
1338 value = lexptr[0] & 0xff;
1339 if (is_byte && value > 127)
1340 error (_("Non-ASCII value in byte string"));
1341 obstack_1grow (&obstack, value);
1346 lvalp->sval.length = obstack_object_size (&obstack);
1347 lvalp->sval.ptr = (const char *) obstack_finish (&obstack);
1348 return is_byte ? BYTESTRING : STRING;
1351 /* Return true if STRING starts with whitespace followed by a digit. */
1354 space_then_number (const char *string)
1356 const char *p = string;
1358 while (p[0] == ' ' || p[0] == '\t')
1363 return *p >= '0' && *p <= '9';
1366 /* Return true if C can start an identifier. */
1369 rust_identifier_start_p (char c)
1371 return ((c >= 'a' && c <= 'z')
1372 || (c >= 'A' && c <= 'Z')
1377 /* Lex an identifier. */
1380 rust_parser::lex_identifier (YYSTYPE *lvalp)
1382 const char *start = lexptr;
1383 unsigned int length;
1384 const struct token_info *token;
1386 int is_gdb_var = lexptr[0] == '$';
1388 gdb_assert (rust_identifier_start_p (lexptr[0]));
1392 /* For the time being this doesn't handle Unicode rules. Non-ASCII
1393 identifiers are gated anyway. */
1394 while ((lexptr[0] >= 'a' && lexptr[0] <= 'z')
1395 || (lexptr[0] >= 'A' && lexptr[0] <= 'Z')
1397 || (is_gdb_var && lexptr[0] == '$')
1398 || (lexptr[0] >= '0' && lexptr[0] <= '9'))
1402 length = lexptr - start;
1404 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
1406 if (length == strlen (identifier_tokens[i].name)
1407 && strncmp (identifier_tokens[i].name, start, length) == 0)
1409 token = &identifier_tokens[i];
1416 if (token->value == 0)
1418 /* Leave the terminating token alone. */
1423 else if (token == NULL
1424 && (strncmp (start, "thread", length) == 0
1425 || strncmp (start, "task", length) == 0)
1426 && space_then_number (lexptr))
1428 /* "task" or "thread" followed by a number terminates the
1429 parse, per gdb rules. */
1434 if (token == NULL || (parse_completion && lexptr[0] == '\0'))
1435 lvalp->sval = make_stoken (copy_name (start, length));
1437 if (parse_completion && lexptr[0] == '\0')
1439 /* Prevent rustyylex from returning two COMPLETE tokens. */
1440 prev_lexptr = lexptr;
1445 return token->value;
1451 /* Lex an operator. */
1454 lex_operator (YYSTYPE *lvalp)
1456 const struct token_info *token = NULL;
1459 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
1461 if (strncmp (operator_tokens[i].name, lexptr,
1462 strlen (operator_tokens[i].name)) == 0)
1464 lexptr += strlen (operator_tokens[i].name);
1465 token = &operator_tokens[i];
1472 lvalp->opcode = token->opcode;
1473 return token->value;
1482 rust_parser::lex_number (YYSTYPE *lvalp)
1484 regmatch_t subexps[NUM_SUBEXPRESSIONS];
1487 int could_be_decimal = 1;
1488 int implicit_i32 = 0;
1489 const char *type_name = NULL;
1492 int type_index = -1;
1495 match = regexec (&number_regex, lexptr, ARRAY_SIZE (subexps), subexps, 0);
1496 /* Failure means the regexp is broken. */
1497 gdb_assert (match == 0);
1499 if (subexps[INT_TEXT].rm_so != -1)
1501 /* Integer part matched. */
1503 end_index = subexps[INT_TEXT].rm_eo;
1504 if (subexps[INT_TYPE].rm_so == -1)
1511 type_index = INT_TYPE;
1512 could_be_decimal = 0;
1515 else if (subexps[FLOAT_TYPE1].rm_so != -1)
1517 /* Found floating point type suffix. */
1518 end_index = subexps[FLOAT_TYPE1].rm_so;
1519 type_index = FLOAT_TYPE1;
1521 else if (subexps[FLOAT_TYPE2].rm_so != -1)
1523 /* Found floating point type suffix. */
1524 end_index = subexps[FLOAT_TYPE2].rm_so;
1525 type_index = FLOAT_TYPE2;
1529 /* Any other floating point match. */
1530 end_index = subexps[0].rm_eo;
1534 /* We need a special case if the final character is ".". In this
1535 case we might need to parse an integer. For example, "23.f()" is
1536 a request for a trait method call, not a syntax error involving
1537 the floating point number "23.". */
1538 gdb_assert (subexps[0].rm_eo > 0);
1539 if (lexptr[subexps[0].rm_eo - 1] == '.')
1541 const char *next = skip_spaces (&lexptr[subexps[0].rm_eo]);
1543 if (rust_identifier_start_p (*next) || *next == '.')
1547 end_index = subexps[0].rm_eo;
1549 could_be_decimal = 1;
1554 /* Compute the type name if we haven't already. */
1555 std::string type_name_holder;
1556 if (type_name == NULL)
1558 gdb_assert (type_index != -1);
1559 type_name_holder = std::string (lexptr + subexps[type_index].rm_so,
1560 (subexps[type_index].rm_eo
1561 - subexps[type_index].rm_so));
1562 type_name = type_name_holder.c_str ();
1565 /* Look up the type. */
1566 type = get_type (type_name);
1568 /* Copy the text of the number and remove the "_"s. */
1570 for (i = 0; i < end_index && lexptr[i]; ++i)
1572 if (lexptr[i] == '_')
1573 could_be_decimal = 0;
1575 number.push_back (lexptr[i]);
1578 /* Advance past the match. */
1579 lexptr += subexps[0].rm_eo;
1581 /* Parse the number. */
1588 if (number[0] == '0')
1590 if (number[1] == 'x')
1592 else if (number[1] == 'o')
1594 else if (number[1] == 'b')
1599 could_be_decimal = 0;
1603 value = strtoul (number.c_str () + offset, NULL, radix);
1604 if (implicit_i32 && value >= ((uint64_t) 1) << 31)
1605 type = get_type ("i64");
1607 lvalp->typed_val_int.val = value;
1608 lvalp->typed_val_int.type = type;
1612 lvalp->typed_val_float.type = type;
1613 bool parsed = parse_float (number.c_str (), number.length (),
1614 lvalp->typed_val_float.type,
1615 lvalp->typed_val_float.val);
1616 gdb_assert (parsed);
1619 return is_integer ? (could_be_decimal ? DECIMAL_INTEGER : INTEGER) : FLOAT;
1625 rustyylex (YYSTYPE *lvalp, rust_parser *parser)
1627 /* Skip all leading whitespace. */
1628 while (lexptr[0] == ' ' || lexptr[0] == '\t' || lexptr[0] == '\r'
1629 || lexptr[0] == '\n')
1632 /* If we hit EOF and we're completing, then return COMPLETE -- maybe
1633 we're completing an empty string at the end of a field_expr.
1634 But, we don't want to return two COMPLETE tokens in a row. */
1635 if (lexptr[0] == '\0' && lexptr == prev_lexptr)
1637 prev_lexptr = lexptr;
1638 if (lexptr[0] == '\0')
1640 if (parse_completion)
1642 lvalp->sval = make_stoken ("");
1648 if (lexptr[0] >= '0' && lexptr[0] <= '9')
1649 return parser->lex_number (lvalp);
1650 else if (lexptr[0] == 'b' && lexptr[1] == '\'')
1651 return parser->lex_character (lvalp);
1652 else if (lexptr[0] == 'b' && lexptr[1] == '"')
1653 return parser->lex_string (lvalp);
1654 else if (lexptr[0] == 'b' && starts_raw_string (lexptr + 1))
1655 return parser->lex_string (lvalp);
1656 else if (starts_raw_string (lexptr))
1657 return parser->lex_string (lvalp);
1658 else if (rust_identifier_start_p (lexptr[0]))
1659 return parser->lex_identifier (lvalp);
1660 else if (lexptr[0] == '"')
1661 return parser->lex_string (lvalp);
1662 else if (lexptr[0] == '\'')
1663 return parser->lex_character (lvalp);
1664 else if (lexptr[0] == '}' || lexptr[0] == ']')
1666 /* Falls through to lex_operator. */
1669 else if (lexptr[0] == '(' || lexptr[0] == '{')
1671 /* Falls through to lex_operator. */
1674 else if (lexptr[0] == ',' && comma_terminates && paren_depth == 0)
1677 return lex_operator (lvalp);
1680 /* Push back a single character to be re-lexed. */
1683 rust_push_back (char c)
1685 /* Can't be called before any lexing. */
1686 gdb_assert (prev_lexptr != NULL);
1689 gdb_assert (*lexptr == c);
1694 /* Make an arbitrary operation and fill in the fields. */
1696 const struct rust_op *
1697 rust_parser::ast_operation (enum exp_opcode opcode, const struct rust_op *left,
1698 const struct rust_op *right)
1700 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1702 result->opcode = opcode;
1703 result->left.op = left;
1704 result->right.op = right;
1709 /* Make a compound assignment operation. */
1711 const struct rust_op *
1712 rust_parser::ast_compound_assignment (enum exp_opcode opcode,
1713 const struct rust_op *left,
1714 const struct rust_op *right)
1716 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1718 result->opcode = opcode;
1719 result->compound_assignment = 1;
1720 result->left.op = left;
1721 result->right.op = right;
1726 /* Make a typed integer literal operation. */
1728 const struct rust_op *
1729 rust_parser::ast_literal (struct typed_val_int val)
1731 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1733 result->opcode = OP_LONG;
1734 result->left.typed_val_int = val;
1739 /* Make a typed floating point literal operation. */
1741 const struct rust_op *
1742 rust_parser::ast_dliteral (struct typed_val_float val)
1744 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1746 result->opcode = OP_FLOAT;
1747 result->left.typed_val_float = val;
1752 /* Make a unary operation. */
1754 const struct rust_op *
1755 rust_parser::ast_unary (enum exp_opcode opcode, const struct rust_op *expr)
1757 return ast_operation (opcode, expr, NULL);
1760 /* Make a cast operation. */
1762 const struct rust_op *
1763 rust_parser::ast_cast (const struct rust_op *expr, const struct rust_op *type)
1765 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1767 result->opcode = UNOP_CAST;
1768 result->left.op = expr;
1769 result->right.op = type;
1774 /* Make a call-like operation. This is nominally a function call, but
1775 when lowering we may discover that it actually represents the
1776 creation of a tuple struct. */
1778 const struct rust_op *
1779 rust_parser::ast_call_ish (enum exp_opcode opcode, const struct rust_op *expr,
1780 rust_op_vector *params)
1782 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1784 result->opcode = opcode;
1785 result->left.op = expr;
1786 result->right.params = params;
1791 /* Make a structure creation operation. */
1793 const struct rust_op *
1794 rust_parser::ast_struct (const struct rust_op *name, rust_set_vector *fields)
1796 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1798 result->opcode = OP_AGGREGATE;
1799 result->left.op = name;
1800 result->right.field_inits = fields;
1805 /* Make an identifier path. */
1807 const struct rust_op *
1808 rust_parser::ast_path (struct stoken path, rust_op_vector *params)
1810 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1812 result->opcode = OP_VAR_VALUE;
1813 result->left.sval = path;
1814 result->right.params = params;
1819 /* Make a string constant operation. */
1821 const struct rust_op *
1822 rust_parser::ast_string (struct stoken str)
1824 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1826 result->opcode = OP_STRING;
1827 result->left.sval = str;
1832 /* Make a field expression. */
1834 const struct rust_op *
1835 rust_parser::ast_structop (const struct rust_op *left, const char *name,
1838 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1840 result->opcode = STRUCTOP_STRUCT;
1841 result->completing = completing;
1842 result->left.op = left;
1843 result->right.sval = make_stoken (name);
1848 /* Make an anonymous struct operation, like 'x.0'. */
1850 const struct rust_op *
1851 rust_parser::ast_structop_anonymous (const struct rust_op *left,
1852 struct typed_val_int number)
1854 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1856 result->opcode = STRUCTOP_ANONYMOUS;
1857 result->left.op = left;
1858 result->right.typed_val_int = number;
1863 /* Make a range operation. */
1865 const struct rust_op *
1866 rust_parser::ast_range (const struct rust_op *lhs, const struct rust_op *rhs,
1869 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1871 result->opcode = OP_RANGE;
1872 result->inclusive = inclusive;
1873 result->left.op = lhs;
1874 result->right.op = rhs;
1879 /* A helper function to make a type-related AST node. */
1882 rust_parser::ast_basic_type (enum type_code typecode)
1884 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1886 result->opcode = OP_TYPE;
1887 result->typecode = typecode;
1891 /* Create an AST node describing an array type. */
1893 const struct rust_op *
1894 rust_parser::ast_array_type (const struct rust_op *lhs,
1895 struct typed_val_int val)
1897 struct rust_op *result = ast_basic_type (TYPE_CODE_ARRAY);
1899 result->left.op = lhs;
1900 result->right.typed_val_int = val;
1904 /* Create an AST node describing a reference type. */
1906 const struct rust_op *
1907 rust_parser::ast_slice_type (const struct rust_op *type)
1909 /* Use TYPE_CODE_COMPLEX just because it is handy. */
1910 struct rust_op *result = ast_basic_type (TYPE_CODE_COMPLEX);
1912 result->left.op = type;
1916 /* Create an AST node describing a reference type. */
1918 const struct rust_op *
1919 rust_parser::ast_reference_type (const struct rust_op *type)
1921 struct rust_op *result = ast_basic_type (TYPE_CODE_REF);
1923 result->left.op = type;
1927 /* Create an AST node describing a pointer type. */
1929 const struct rust_op *
1930 rust_parser::ast_pointer_type (const struct rust_op *type, int is_mut)
1932 struct rust_op *result = ast_basic_type (TYPE_CODE_PTR);
1934 result->left.op = type;
1935 /* For the time being we ignore is_mut. */
1939 /* Create an AST node describing a function type. */
1941 const struct rust_op *
1942 rust_parser::ast_function_type (const struct rust_op *rtype,
1943 rust_op_vector *params)
1945 struct rust_op *result = ast_basic_type (TYPE_CODE_FUNC);
1947 result->left.op = rtype;
1948 result->right.params = params;
1952 /* Create an AST node describing a tuple type. */
1954 const struct rust_op *
1955 rust_parser::ast_tuple_type (rust_op_vector *params)
1957 struct rust_op *result = ast_basic_type (TYPE_CODE_STRUCT);
1959 result->left.params = params;
1963 /* A helper to appropriately munge NAME and BLOCK depending on the
1964 presence of a leading "::". */
1967 munge_name_and_block (const char **name, const struct block **block)
1969 /* If it is a global reference, skip the current block in favor of
1970 the static block. */
1971 if (strncmp (*name, "::", 2) == 0)
1974 *block = block_static_block (*block);
1978 /* Like lookup_symbol, but handles Rust namespace conventions, and
1979 doesn't require field_of_this_result. */
1981 static struct block_symbol
1982 rust_lookup_symbol (const char *name, const struct block *block,
1983 const domain_enum domain)
1985 struct block_symbol result;
1987 munge_name_and_block (&name, &block);
1989 result = lookup_symbol (name, block, domain, NULL);
1990 if (result.symbol != NULL)
1991 update_innermost_block (result);
1995 /* Look up a type, following Rust namespace conventions. */
1998 rust_parser::rust_lookup_type (const char *name, const struct block *block)
2000 struct block_symbol result;
2003 munge_name_and_block (&name, &block);
2005 result = lookup_symbol (name, block, STRUCT_DOMAIN, NULL);
2006 if (result.symbol != NULL)
2008 update_innermost_block (result);
2009 return SYMBOL_TYPE (result.symbol);
2012 type = lookup_typename (language (), arch (), name, NULL, 1);
2016 /* Last chance, try a built-in type. */
2017 return language_lookup_primitive_type (language (), arch (), name);
2020 /* Convert a vector of rust_ops representing types to a vector of
2023 std::vector<struct type *>
2024 rust_parser::convert_params_to_types (rust_op_vector *params)
2026 std::vector<struct type *> result;
2028 if (params != nullptr)
2030 for (const rust_op *op : *params)
2031 result.push_back (convert_ast_to_type (op));
2037 /* Convert a rust_op representing a type to a struct type *. */
2040 rust_parser::convert_ast_to_type (const struct rust_op *operation)
2042 struct type *type, *result = NULL;
2044 if (operation->opcode == OP_VAR_VALUE)
2046 const char *varname = convert_name (operation);
2048 result = rust_lookup_type (varname, expression_context_block);
2050 error (_("No typed name '%s' in current context"), varname);
2054 gdb_assert (operation->opcode == OP_TYPE);
2056 switch (operation->typecode)
2058 case TYPE_CODE_ARRAY:
2059 type = convert_ast_to_type (operation->left.op);
2060 if (operation->right.typed_val_int.val < 0)
2061 error (_("Negative array length"));
2062 result = lookup_array_range_type (type, 0,
2063 operation->right.typed_val_int.val - 1);
2066 case TYPE_CODE_COMPLEX:
2068 struct type *usize = get_type ("usize");
2070 type = convert_ast_to_type (operation->left.op);
2071 result = rust_slice_type ("&[*gdb*]", type, usize);
2077 /* For now we treat &x and *x identically. */
2078 type = convert_ast_to_type (operation->left.op);
2079 result = lookup_pointer_type (type);
2082 case TYPE_CODE_FUNC:
2084 std::vector<struct type *> args
2085 (convert_params_to_types (operation->right.params));
2086 struct type **argtypes = NULL;
2088 type = convert_ast_to_type (operation->left.op);
2090 argtypes = args.data ();
2093 = lookup_function_type_with_arguments (type, args.size (),
2095 result = lookup_pointer_type (result);
2099 case TYPE_CODE_STRUCT:
2101 std::vector<struct type *> args
2102 (convert_params_to_types (operation->left.params));
2106 obstack_1grow (&obstack, '(');
2107 for (i = 0; i < args.size (); ++i)
2109 std::string type_name = type_to_string (args[i]);
2112 obstack_1grow (&obstack, ',');
2113 obstack_grow_str (&obstack, type_name.c_str ());
2116 obstack_grow_str0 (&obstack, ")");
2117 name = (const char *) obstack_finish (&obstack);
2119 /* We don't allow creating new tuple types (yet), but we do
2120 allow looking up existing tuple types. */
2121 result = rust_lookup_type (name, expression_context_block);
2123 error (_("could not find tuple type '%s'"), name);
2128 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_type");
2131 gdb_assert (result != NULL);
2135 /* A helper function to turn a rust_op representing a name into a full
2136 name. This applies generic arguments as needed. The returned name
2137 is allocated on the work obstack. */
2140 rust_parser::convert_name (const struct rust_op *operation)
2144 gdb_assert (operation->opcode == OP_VAR_VALUE);
2146 if (operation->right.params == NULL)
2147 return operation->left.sval.ptr;
2149 std::vector<struct type *> types
2150 (convert_params_to_types (operation->right.params));
2152 obstack_grow_str (&obstack, operation->left.sval.ptr);
2153 obstack_1grow (&obstack, '<');
2154 for (i = 0; i < types.size (); ++i)
2156 std::string type_name = type_to_string (types[i]);
2159 obstack_1grow (&obstack, ',');
2161 obstack_grow_str (&obstack, type_name.c_str ());
2163 obstack_grow_str0 (&obstack, ">");
2165 return (const char *) obstack_finish (&obstack);
2168 /* A helper function that converts a vec of rust_ops to a gdb
2172 rust_parser::convert_params_to_expression (rust_op_vector *params,
2173 const struct rust_op *top)
2175 for (const rust_op *elem : *params)
2176 convert_ast_to_expression (elem, top);
2179 /* Lower a rust_op to a gdb expression. STATE is the parser state.
2180 OPERATION is the operation to lower. TOP is a pointer to the
2181 top-most operation; it is used to handle the special case where the
2182 top-most expression is an identifier and can be optionally lowered
2183 to OP_TYPE. WANT_TYPE is a flag indicating that, if the expression
2184 is the name of a type, then emit an OP_TYPE for it (rather than
2185 erroring). If WANT_TYPE is set, then the similar TOP handling is
2189 rust_parser::convert_ast_to_expression (const struct rust_op *operation,
2190 const struct rust_op *top,
2193 switch (operation->opcode)
2196 write_exp_elt_opcode (pstate, OP_LONG);
2197 write_exp_elt_type (pstate, operation->left.typed_val_int.type);
2198 write_exp_elt_longcst (pstate, operation->left.typed_val_int.val);
2199 write_exp_elt_opcode (pstate, OP_LONG);
2203 write_exp_elt_opcode (pstate, OP_FLOAT);
2204 write_exp_elt_type (pstate, operation->left.typed_val_float.type);
2205 write_exp_elt_floatcst (pstate, operation->left.typed_val_float.val);
2206 write_exp_elt_opcode (pstate, OP_FLOAT);
2209 case STRUCTOP_STRUCT:
2211 convert_ast_to_expression (operation->left.op, top);
2213 if (operation->completing)
2214 mark_struct_expression (pstate);
2215 write_exp_elt_opcode (pstate, STRUCTOP_STRUCT);
2216 write_exp_string (pstate, operation->right.sval);
2217 write_exp_elt_opcode (pstate, STRUCTOP_STRUCT);
2221 case STRUCTOP_ANONYMOUS:
2223 convert_ast_to_expression (operation->left.op, top);
2225 write_exp_elt_opcode (pstate, STRUCTOP_ANONYMOUS);
2226 write_exp_elt_longcst (pstate, operation->right.typed_val_int.val);
2227 write_exp_elt_opcode (pstate, STRUCTOP_ANONYMOUS);
2232 convert_ast_to_expression (operation->left.op, top, true);
2233 write_exp_elt_opcode (pstate, UNOP_SIZEOF);
2238 case UNOP_COMPLEMENT:
2241 convert_ast_to_expression (operation->left.op, top);
2242 write_exp_elt_opcode (pstate, operation->opcode);
2245 case BINOP_SUBSCRIPT:
2252 case BINOP_BITWISE_AND:
2253 case BINOP_BITWISE_IOR:
2254 case BINOP_BITWISE_XOR:
2257 case BINOP_LOGICAL_OR:
2258 case BINOP_LOGICAL_AND:
2260 case BINOP_NOTEQUAL:
2267 convert_ast_to_expression (operation->left.op, top);
2268 convert_ast_to_expression (operation->right.op, top);
2269 if (operation->compound_assignment)
2271 write_exp_elt_opcode (pstate, BINOP_ASSIGN_MODIFY);
2272 write_exp_elt_opcode (pstate, operation->opcode);
2273 write_exp_elt_opcode (pstate, BINOP_ASSIGN_MODIFY);
2276 write_exp_elt_opcode (pstate, operation->opcode);
2278 if (operation->compound_assignment
2279 || operation->opcode == BINOP_ASSIGN)
2283 type = language_lookup_primitive_type (parse_language (pstate),
2284 parse_gdbarch (pstate),
2287 write_exp_elt_opcode (pstate, OP_LONG);
2288 write_exp_elt_type (pstate, type);
2289 write_exp_elt_longcst (pstate, 0);
2290 write_exp_elt_opcode (pstate, OP_LONG);
2292 write_exp_elt_opcode (pstate, BINOP_COMMA);
2298 struct type *type = convert_ast_to_type (operation->right.op);
2300 convert_ast_to_expression (operation->left.op, top);
2301 write_exp_elt_opcode (pstate, UNOP_CAST);
2302 write_exp_elt_type (pstate, type);
2303 write_exp_elt_opcode (pstate, UNOP_CAST);
2309 if (operation->left.op->opcode == OP_VAR_VALUE)
2312 const char *varname = convert_name (operation->left.op);
2314 type = rust_lookup_type (varname, expression_context_block);
2317 /* This is actually a tuple struct expression, not a
2319 rust_op_vector *params = operation->right.params;
2321 if (TYPE_CODE (type) != TYPE_CODE_NAMESPACE)
2323 if (!rust_tuple_struct_type_p (type))
2324 error (_("Type %s is not a tuple struct"), varname);
2326 for (int i = 0; i < params->size (); ++i)
2328 char *cell = get_print_cell ();
2330 xsnprintf (cell, PRINT_CELL_SIZE, "__%d", i);
2331 write_exp_elt_opcode (pstate, OP_NAME);
2332 write_exp_string (pstate, make_stoken (cell));
2333 write_exp_elt_opcode (pstate, OP_NAME);
2335 convert_ast_to_expression ((*params)[i], top);
2338 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2339 write_exp_elt_type (pstate, type);
2340 write_exp_elt_longcst (pstate, 2 * params->size ());
2341 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2346 convert_ast_to_expression (operation->left.op, top);
2347 convert_params_to_expression (operation->right.params, top);
2348 write_exp_elt_opcode (pstate, OP_FUNCALL);
2349 write_exp_elt_longcst (pstate, operation->right.params->size ());
2350 write_exp_elt_longcst (pstate, OP_FUNCALL);
2355 gdb_assert (operation->left.op == NULL);
2356 convert_params_to_expression (operation->right.params, top);
2357 write_exp_elt_opcode (pstate, OP_ARRAY);
2358 write_exp_elt_longcst (pstate, 0);
2359 write_exp_elt_longcst (pstate, operation->right.params->size () - 1);
2360 write_exp_elt_longcst (pstate, OP_ARRAY);
2365 struct block_symbol sym;
2366 const char *varname;
2368 if (operation->left.sval.ptr[0] == '$')
2370 write_dollar_variable (pstate, operation->left.sval);
2374 varname = convert_name (operation);
2375 sym = rust_lookup_symbol (varname, expression_context_block,
2377 if (sym.symbol != NULL && SYMBOL_CLASS (sym.symbol) != LOC_TYPEDEF)
2379 write_exp_elt_opcode (pstate, OP_VAR_VALUE);
2380 write_exp_elt_block (pstate, sym.block);
2381 write_exp_elt_sym (pstate, sym.symbol);
2382 write_exp_elt_opcode (pstate, OP_VAR_VALUE);
2386 struct type *type = NULL;
2388 if (sym.symbol != NULL)
2390 gdb_assert (SYMBOL_CLASS (sym.symbol) == LOC_TYPEDEF);
2391 type = SYMBOL_TYPE (sym.symbol);
2394 type = rust_lookup_type (varname, expression_context_block);
2396 error (_("No symbol '%s' in current context"), varname);
2399 && TYPE_CODE (type) == TYPE_CODE_STRUCT
2400 && TYPE_NFIELDS (type) == 0)
2402 /* A unit-like struct. */
2403 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2404 write_exp_elt_type (pstate, type);
2405 write_exp_elt_longcst (pstate, 0);
2406 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2408 else if (want_type || operation == top)
2410 write_exp_elt_opcode (pstate, OP_TYPE);
2411 write_exp_elt_type (pstate, type);
2412 write_exp_elt_opcode (pstate, OP_TYPE);
2415 error (_("Found type '%s', which can't be "
2416 "evaluated in this context"),
2425 rust_set_vector *fields = operation->right.field_inits;
2430 for (const set_field &init : *fields)
2432 if (init.name.ptr != NULL)
2434 write_exp_elt_opcode (pstate, OP_NAME);
2435 write_exp_string (pstate, init.name);
2436 write_exp_elt_opcode (pstate, OP_NAME);
2440 convert_ast_to_expression (init.init, top);
2443 if (init.name.ptr == NULL)
2445 /* This is handled differently from Ada in our
2447 write_exp_elt_opcode (pstate, OP_OTHERS);
2451 name = convert_name (operation->left.op);
2452 type = rust_lookup_type (name, expression_context_block);
2454 error (_("Could not find type '%s'"), operation->left.sval.ptr);
2456 if (TYPE_CODE (type) != TYPE_CODE_STRUCT
2457 || rust_tuple_type_p (type)
2458 || rust_tuple_struct_type_p (type))
2459 error (_("Struct expression applied to non-struct type"));
2461 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2462 write_exp_elt_type (pstate, type);
2463 write_exp_elt_longcst (pstate, length);
2464 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2470 write_exp_elt_opcode (pstate, OP_STRING);
2471 write_exp_string (pstate, operation->left.sval);
2472 write_exp_elt_opcode (pstate, OP_STRING);
2478 enum range_type kind = BOTH_BOUND_DEFAULT;
2480 if (operation->left.op != NULL)
2482 convert_ast_to_expression (operation->left.op, top);
2483 kind = HIGH_BOUND_DEFAULT;
2485 if (operation->right.op != NULL)
2487 convert_ast_to_expression (operation->right.op, top);
2488 if (kind == BOTH_BOUND_DEFAULT)
2489 kind = (operation->inclusive
2490 ? LOW_BOUND_DEFAULT : LOW_BOUND_DEFAULT_EXCLUSIVE);
2493 gdb_assert (kind == HIGH_BOUND_DEFAULT);
2494 kind = (operation->inclusive
2495 ? NONE_BOUND_DEFAULT : NONE_BOUND_DEFAULT_EXCLUSIVE);
2500 /* Nothing should make an inclusive range without an upper
2502 gdb_assert (!operation->inclusive);
2505 write_exp_elt_opcode (pstate, OP_RANGE);
2506 write_exp_elt_longcst (pstate, kind);
2507 write_exp_elt_opcode (pstate, OP_RANGE);
2512 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_expression");
2518 /* The parser as exposed to gdb. */
2521 rust_parse (struct parser_state *state)
2525 /* This sets various globals and also clears them on
2527 rust_parser parser (state);
2529 result = rustyyparse (&parser);
2531 if (!result || (parse_completion && parser.rust_ast != NULL))
2532 parser.convert_ast_to_expression (parser.rust_ast, parser.rust_ast);
2537 /* The parser error handler. */
2540 rustyyerror (rust_parser *parser, const char *msg)
2542 const char *where = prev_lexptr ? prev_lexptr : lexptr;
2543 error (_("%s in expression, near `%s'."), msg, where);
2550 /* Initialize the lexer for testing. */
2553 rust_lex_test_init (const char *input)
2560 /* A test helper that lexes a string, expecting a single token. It
2561 returns the lexer data for this token. */
2564 rust_lex_test_one (rust_parser *parser, const char *input, int expected)
2569 rust_lex_test_init (input);
2571 token = rustyylex (&result, parser);
2572 SELF_CHECK (token == expected);
2577 token = rustyylex (&ignore, parser);
2578 SELF_CHECK (token == 0);
2584 /* Test that INPUT lexes as the integer VALUE. */
2587 rust_lex_int_test (rust_parser *parser, const char *input, int value, int kind)
2589 RUSTSTYPE result = rust_lex_test_one (parser, input, kind);
2590 SELF_CHECK (result.typed_val_int.val == value);
2593 /* Test that INPUT throws an exception with text ERR. */
2596 rust_lex_exception_test (rust_parser *parser, const char *input,
2601 /* The "kind" doesn't matter. */
2602 rust_lex_test_one (parser, input, DECIMAL_INTEGER);
2605 CATCH (except, RETURN_MASK_ERROR)
2607 SELF_CHECK (strcmp (except.message, err) == 0);
2612 /* Test that INPUT lexes as the identifier, string, or byte-string
2613 VALUE. KIND holds the expected token kind. */
2616 rust_lex_stringish_test (rust_parser *parser, const char *input,
2617 const char *value, int kind)
2619 RUSTSTYPE result = rust_lex_test_one (parser, input, kind);
2620 SELF_CHECK (result.sval.length == strlen (value));
2621 SELF_CHECK (strncmp (result.sval.ptr, value, result.sval.length) == 0);
2624 /* Helper to test that a string parses as a given token sequence. */
2627 rust_lex_test_sequence (rust_parser *parser, const char *input, int len,
2628 const int expected[])
2635 for (i = 0; i < len; ++i)
2638 int token = rustyylex (&ignore, parser);
2640 SELF_CHECK (token == expected[i]);
2644 /* Tests for an integer-parsing corner case. */
2647 rust_lex_test_trailing_dot (rust_parser *parser)
2649 const int expected1[] = { DECIMAL_INTEGER, '.', IDENT, '(', ')', 0 };
2650 const int expected2[] = { INTEGER, '.', IDENT, '(', ')', 0 };
2651 const int expected3[] = { FLOAT, EQEQ, '(', ')', 0 };
2652 const int expected4[] = { DECIMAL_INTEGER, DOTDOT, DECIMAL_INTEGER, 0 };
2654 rust_lex_test_sequence (parser, "23.g()", ARRAY_SIZE (expected1), expected1);
2655 rust_lex_test_sequence (parser, "23_0.g()", ARRAY_SIZE (expected2),
2657 rust_lex_test_sequence (parser, "23.==()", ARRAY_SIZE (expected3),
2659 rust_lex_test_sequence (parser, "23..25", ARRAY_SIZE (expected4), expected4);
2662 /* Tests of completion. */
2665 rust_lex_test_completion (rust_parser *parser)
2667 const int expected[] = { IDENT, '.', COMPLETE, 0 };
2669 parse_completion = 1;
2671 rust_lex_test_sequence (parser, "something.wha", ARRAY_SIZE (expected),
2673 rust_lex_test_sequence (parser, "something.", ARRAY_SIZE (expected),
2676 parse_completion = 0;
2679 /* Test pushback. */
2682 rust_lex_test_push_back (rust_parser *parser)
2687 rust_lex_test_init (">>=");
2689 token = rustyylex (&lval, parser);
2690 SELF_CHECK (token == COMPOUND_ASSIGN);
2691 SELF_CHECK (lval.opcode == BINOP_RSH);
2693 rust_push_back ('=');
2695 token = rustyylex (&lval, parser);
2696 SELF_CHECK (token == '=');
2698 token = rustyylex (&lval, parser);
2699 SELF_CHECK (token == 0);
2702 /* Unit test the lexer. */
2705 rust_lex_tests (void)
2709 // Set up dummy "parser", so that rust_type works.
2710 struct parser_state ps (0, &rust_language_defn, target_gdbarch ());
2711 rust_parser parser (&ps);
2713 rust_lex_test_one (&parser, "", 0);
2714 rust_lex_test_one (&parser, " \t \n \r ", 0);
2715 rust_lex_test_one (&parser, "thread 23", 0);
2716 rust_lex_test_one (&parser, "task 23", 0);
2717 rust_lex_test_one (&parser, "th 104", 0);
2718 rust_lex_test_one (&parser, "ta 97", 0);
2720 rust_lex_int_test (&parser, "'z'", 'z', INTEGER);
2721 rust_lex_int_test (&parser, "'\\xff'", 0xff, INTEGER);
2722 rust_lex_int_test (&parser, "'\\u{1016f}'", 0x1016f, INTEGER);
2723 rust_lex_int_test (&parser, "b'z'", 'z', INTEGER);
2724 rust_lex_int_test (&parser, "b'\\xfe'", 0xfe, INTEGER);
2725 rust_lex_int_test (&parser, "b'\\xFE'", 0xfe, INTEGER);
2726 rust_lex_int_test (&parser, "b'\\xfE'", 0xfe, INTEGER);
2728 /* Test all escapes in both modes. */
2729 rust_lex_int_test (&parser, "'\\n'", '\n', INTEGER);
2730 rust_lex_int_test (&parser, "'\\r'", '\r', INTEGER);
2731 rust_lex_int_test (&parser, "'\\t'", '\t', INTEGER);
2732 rust_lex_int_test (&parser, "'\\\\'", '\\', INTEGER);
2733 rust_lex_int_test (&parser, "'\\0'", '\0', INTEGER);
2734 rust_lex_int_test (&parser, "'\\''", '\'', INTEGER);
2735 rust_lex_int_test (&parser, "'\\\"'", '"', INTEGER);
2737 rust_lex_int_test (&parser, "b'\\n'", '\n', INTEGER);
2738 rust_lex_int_test (&parser, "b'\\r'", '\r', INTEGER);
2739 rust_lex_int_test (&parser, "b'\\t'", '\t', INTEGER);
2740 rust_lex_int_test (&parser, "b'\\\\'", '\\', INTEGER);
2741 rust_lex_int_test (&parser, "b'\\0'", '\0', INTEGER);
2742 rust_lex_int_test (&parser, "b'\\''", '\'', INTEGER);
2743 rust_lex_int_test (&parser, "b'\\\"'", '"', INTEGER);
2745 rust_lex_exception_test (&parser, "'z", "Unterminated character literal");
2746 rust_lex_exception_test (&parser, "b'\\x0'", "Not enough hex digits seen");
2747 rust_lex_exception_test (&parser, "b'\\u{0}'",
2748 "Unicode escape in byte literal");
2749 rust_lex_exception_test (&parser, "'\\x0'", "Not enough hex digits seen");
2750 rust_lex_exception_test (&parser, "'\\u0'", "Missing '{' in Unicode escape");
2751 rust_lex_exception_test (&parser, "'\\u{0", "Missing '}' in Unicode escape");
2752 rust_lex_exception_test (&parser, "'\\u{0000007}", "Overlong hex escape");
2753 rust_lex_exception_test (&parser, "'\\u{}", "Not enough hex digits seen");
2754 rust_lex_exception_test (&parser, "'\\Q'", "Invalid escape \\Q in literal");
2755 rust_lex_exception_test (&parser, "b'\\Q'", "Invalid escape \\Q in literal");
2757 rust_lex_int_test (&parser, "23", 23, DECIMAL_INTEGER);
2758 rust_lex_int_test (&parser, "2_344__29", 234429, INTEGER);
2759 rust_lex_int_test (&parser, "0x1f", 0x1f, INTEGER);
2760 rust_lex_int_test (&parser, "23usize", 23, INTEGER);
2761 rust_lex_int_test (&parser, "23i32", 23, INTEGER);
2762 rust_lex_int_test (&parser, "0x1_f", 0x1f, INTEGER);
2763 rust_lex_int_test (&parser, "0b1_101011__", 0x6b, INTEGER);
2764 rust_lex_int_test (&parser, "0o001177i64", 639, INTEGER);
2766 rust_lex_test_trailing_dot (&parser);
2768 rust_lex_test_one (&parser, "23.", FLOAT);
2769 rust_lex_test_one (&parser, "23.99f32", FLOAT);
2770 rust_lex_test_one (&parser, "23e7", FLOAT);
2771 rust_lex_test_one (&parser, "23E-7", FLOAT);
2772 rust_lex_test_one (&parser, "23e+7", FLOAT);
2773 rust_lex_test_one (&parser, "23.99e+7f64", FLOAT);
2774 rust_lex_test_one (&parser, "23.82f32", FLOAT);
2776 rust_lex_stringish_test (&parser, "hibob", "hibob", IDENT);
2777 rust_lex_stringish_test (&parser, "hibob__93", "hibob__93", IDENT);
2778 rust_lex_stringish_test (&parser, "thread", "thread", IDENT);
2780 rust_lex_stringish_test (&parser, "\"string\"", "string", STRING);
2781 rust_lex_stringish_test (&parser, "\"str\\ting\"", "str\ting", STRING);
2782 rust_lex_stringish_test (&parser, "\"str\\\"ing\"", "str\"ing", STRING);
2783 rust_lex_stringish_test (&parser, "r\"str\\ing\"", "str\\ing", STRING);
2784 rust_lex_stringish_test (&parser, "r#\"str\\ting\"#", "str\\ting", STRING);
2785 rust_lex_stringish_test (&parser, "r###\"str\\\"ing\"###", "str\\\"ing",
2788 rust_lex_stringish_test (&parser, "b\"string\"", "string", BYTESTRING);
2789 rust_lex_stringish_test (&parser, "b\"\x73tring\"", "string", BYTESTRING);
2790 rust_lex_stringish_test (&parser, "b\"str\\\"ing\"", "str\"ing", BYTESTRING);
2791 rust_lex_stringish_test (&parser, "br####\"\\x73tring\"####", "\\x73tring",
2794 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
2795 rust_lex_test_one (&parser, identifier_tokens[i].name,
2796 identifier_tokens[i].value);
2798 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
2799 rust_lex_test_one (&parser, operator_tokens[i].name,
2800 operator_tokens[i].value);
2802 rust_lex_test_completion (&parser);
2803 rust_lex_test_push_back (&parser);
2806 #endif /* GDB_SELF_TEST */
2809 _initialize_rust_exp (void)
2811 int code = regcomp (&number_regex, number_regex_text, REG_EXTENDED);
2812 /* If the regular expression was incorrect, it was a programming
2814 gdb_assert (code == 0);
2817 selftests::register_test ("rust-lex", rust_lex_tests);