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 pstate->language ();
211 /* Return the parser's gdbarch. */
212 struct gdbarch *arch () const
214 return pstate->gdbarch ();
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;
304 /* Depth of parentheses. */
308 /* Rust AST operations. We build a tree of these; then lower them to
309 gdb expressions when parsing has completed. */
314 enum exp_opcode opcode;
315 /* If OPCODE is OP_TYPE, then this holds information about what type
316 is described by this node. */
317 enum type_code typecode;
318 /* Indicates whether OPCODE actually represents a compound
319 assignment. For example, if OPCODE is GTGT and this is false,
320 then this rust_op represents an ordinary ">>"; but if this is
321 true, then this rust_op represents ">>=". Unused in other
323 unsigned int compound_assignment : 1;
324 /* Only used by a field expression; if set, indicates that the field
325 name occurred at the end of the expression and is eligible for
327 unsigned int completing : 1;
328 /* For OP_RANGE, indicates whether the range is inclusive or
330 unsigned int inclusive : 1;
331 /* Operands of expression. Which one is used and how depends on the
332 particular opcode. */
341 %token <sval> COMPLETE
342 %token <typed_val_int> INTEGER
343 %token <typed_val_int> DECIMAL_INTEGER
345 %token <sval> BYTESTRING
346 %token <typed_val_float> FLOAT
347 %token <opcode> COMPOUND_ASSIGN
349 /* Keyword tokens. */
350 %token <voidval> KW_AS
351 %token <voidval> KW_IF
352 %token <voidval> KW_TRUE
353 %token <voidval> KW_FALSE
354 %token <voidval> KW_SUPER
355 %token <voidval> KW_SELF
356 %token <voidval> KW_MUT
357 %token <voidval> KW_EXTERN
358 %token <voidval> KW_CONST
359 %token <voidval> KW_FN
360 %token <voidval> KW_SIZEOF
362 /* Operator tokens. */
363 %token <voidval> DOTDOT
364 %token <voidval> DOTDOTEQ
365 %token <voidval> OROR
366 %token <voidval> ANDAND
367 %token <voidval> EQEQ
368 %token <voidval> NOTEQ
369 %token <voidval> LTEQ
370 %token <voidval> GTEQ
371 %token <voidval> LSH RSH
372 %token <voidval> COLONCOLON
373 %token <voidval> ARROW
376 %type <op> path_for_expr
377 %type <op> identifier_path_for_expr
378 %type <op> path_for_type
379 %type <op> identifier_path_for_type
380 %type <op> just_identifiers_for_type
382 %type <params> maybe_type_list
383 %type <params> type_list
385 %type <depth> super_path
389 %type <op> field_expr
392 %type <op> binop_expr
393 %type <op> binop_expr_expr
394 %type <op> type_cast_expr
395 %type <op> assignment_expr
396 %type <op> compound_assignment_expr
397 %type <op> paren_expr
400 %type <op> tuple_expr
402 %type <op> struct_expr
403 %type <op> array_expr
404 %type <op> range_expr
406 %type <params> expr_list
407 %type <params> maybe_expr_list
408 %type <params> paren_expr_list
410 %type <field_inits> struct_expr_list
411 %type <one_field_init> struct_expr_tail
414 %nonassoc DOTDOT DOTDOTEQ
415 %right '=' COMPOUND_ASSIGN
418 %nonassoc EQEQ NOTEQ '<' '>' LTEQ GTEQ
426 /* These could be %precedence in Bison, but that isn't a yacc
437 /* If we are completing and see a valid parse,
438 rust_ast will already have been set. */
439 if (parser->rust_ast == NULL)
440 parser->rust_ast = $1;
444 /* Note that the Rust grammar includes a method_call_expr, but we
445 handle this differently, to avoid a shift/reduce conflict with
457 | unop_expr /* Must precede call_expr because of ambiguity with
465 '(' expr ',' maybe_expr_list ')'
468 error (_("Tuple expressions not supported yet"));
475 struct typed_val_int val;
478 = (language_lookup_primitive_type
479 (parser->language (), parser->arch (),
482 $$ = parser->ast_literal (val);
486 /* To avoid a shift/reduce conflict with call_expr, we don't handle
487 tuple struct expressions here, but instead when examining the
490 path_for_expr '{' struct_expr_list '}'
491 { $$ = parser->ast_struct ($1, $3); }
518 sf.init = parser->ast_path ($1, NULL);
526 $$ = parser->new_set_vector ();
530 rust_set_vector *result = parser->new_set_vector ();
531 result->push_back ($1);
534 | IDENT ':' expr ',' struct_expr_list
543 | IDENT ',' struct_expr_list
548 sf.init = parser->ast_path ($1, NULL);
555 '[' KW_MUT expr_list ']'
556 { $$ = parser->ast_call_ish (OP_ARRAY, NULL, $3); }
558 { $$ = parser->ast_call_ish (OP_ARRAY, NULL, $2); }
559 | '[' KW_MUT expr ';' expr ']'
560 { $$ = parser->ast_operation (OP_RUST_ARRAY, $3, $5); }
561 | '[' expr ';' expr ']'
562 { $$ = parser->ast_operation (OP_RUST_ARRAY, $2, $4); }
567 { $$ = parser->ast_range ($1, NULL, false); }
569 { $$ = parser->ast_range ($1, $3, false); }
571 { $$ = parser->ast_range ($1, $3, true); }
573 { $$ = parser->ast_range (NULL, $2, false); }
575 { $$ = parser->ast_range (NULL, $2, true); }
577 { $$ = parser->ast_range (NULL, NULL, false); }
582 { $$ = parser->ast_literal ($1); }
584 { $$ = parser->ast_literal ($1); }
586 { $$ = parser->ast_dliteral ($1); }
589 struct set_field field;
590 struct typed_val_int val;
593 rust_set_vector *fields = parser->new_set_vector ();
595 /* Wrap the raw string in the &str struct. */
596 field.name.ptr = "data_ptr";
597 field.name.length = strlen (field.name.ptr);
598 field.init = parser->ast_unary (UNOP_ADDR,
599 parser->ast_string ($1));
600 fields->push_back (field);
602 val.type = parser->get_type ("usize");
605 field.name.ptr = "length";
606 field.name.length = strlen (field.name.ptr);
607 field.init = parser->ast_literal (val);
608 fields->push_back (field);
611 token.length = strlen (token.ptr);
612 $$ = parser->ast_struct (parser->ast_path (token, NULL),
616 { $$ = parser->ast_string ($1); }
619 struct typed_val_int val;
621 val.type = language_bool_type (parser->language (),
624 $$ = parser->ast_literal (val);
628 struct typed_val_int val;
630 val.type = language_bool_type (parser->language (),
633 $$ = parser->ast_literal (val);
639 { $$ = parser->ast_structop ($1, $3.ptr, 0); }
642 $$ = parser->ast_structop ($1, $3.ptr, 1);
643 parser->rust_ast = $$;
645 | expr '.' DECIMAL_INTEGER
646 { $$ = parser->ast_structop_anonymous ($1, $3); }
651 { $$ = parser->ast_operation (BINOP_SUBSCRIPT, $1, $3); }
656 { $$ = parser->ast_unary (UNOP_PLUS, $2); }
658 | '-' expr %prec UNARY
659 { $$ = parser->ast_unary (UNOP_NEG, $2); }
661 | '!' expr %prec UNARY
663 /* Note that we provide a Rust-specific evaluator
664 override for UNOP_COMPLEMENT, so it can do the
665 right thing for both bool and integral
667 $$ = parser->ast_unary (UNOP_COMPLEMENT, $2);
670 | '*' expr %prec UNARY
671 { $$ = parser->ast_unary (UNOP_IND, $2); }
673 | '&' expr %prec UNARY
674 { $$ = parser->ast_unary (UNOP_ADDR, $2); }
676 | '&' KW_MUT expr %prec UNARY
677 { $$ = parser->ast_unary (UNOP_ADDR, $3); }
678 | KW_SIZEOF '(' expr ')' %prec UNARY
679 { $$ = parser->ast_unary (UNOP_SIZEOF, $3); }
686 | compound_assignment_expr
691 { $$ = parser->ast_operation (BINOP_MUL, $1, $3); }
694 { $$ = parser->ast_operation (BINOP_REPEAT, $1, $3); }
697 { $$ = parser->ast_operation (BINOP_DIV, $1, $3); }
700 { $$ = parser->ast_operation (BINOP_REM, $1, $3); }
703 { $$ = parser->ast_operation (BINOP_LESS, $1, $3); }
706 { $$ = parser->ast_operation (BINOP_GTR, $1, $3); }
709 { $$ = parser->ast_operation (BINOP_BITWISE_AND, $1, $3); }
712 { $$ = parser->ast_operation (BINOP_BITWISE_IOR, $1, $3); }
715 { $$ = parser->ast_operation (BINOP_BITWISE_XOR, $1, $3); }
718 { $$ = parser->ast_operation (BINOP_ADD, $1, $3); }
721 { $$ = parser->ast_operation (BINOP_SUB, $1, $3); }
724 { $$ = parser->ast_operation (BINOP_LOGICAL_OR, $1, $3); }
727 { $$ = parser->ast_operation (BINOP_LOGICAL_AND, $1, $3); }
730 { $$ = parser->ast_operation (BINOP_EQUAL, $1, $3); }
733 { $$ = parser->ast_operation (BINOP_NOTEQUAL, $1, $3); }
736 { $$ = parser->ast_operation (BINOP_LEQ, $1, $3); }
739 { $$ = parser->ast_operation (BINOP_GEQ, $1, $3); }
742 { $$ = parser->ast_operation (BINOP_LSH, $1, $3); }
745 { $$ = parser->ast_operation (BINOP_RSH, $1, $3); }
750 { $$ = parser->ast_cast ($1, $3); }
755 { $$ = parser->ast_operation (BINOP_ASSIGN, $1, $3); }
758 compound_assignment_expr:
759 expr COMPOUND_ASSIGN expr
760 { $$ = parser->ast_compound_assignment ($2, $1, $3); }
772 $$ = parser->new_op_vector ();
785 /* The result can't be NULL. */
786 $$ = parser->new_op_vector ();
793 '(' maybe_expr_list ')'
799 { $$ = parser->ast_call_ish (OP_FUNCALL, $1, $2); }
810 | super_path KW_SUPER COLONCOLON
818 { $$ = parser->ast_path ($1, NULL); }
820 { $$ = parser->ast_path (make_stoken ("self"), NULL); }
824 identifier_path_for_expr
825 | KW_SELF COLONCOLON identifier_path_for_expr
826 { $$ = parser->super_name ($3, 0); }
827 | maybe_self_path super_path identifier_path_for_expr
828 { $$ = parser->super_name ($3, $2); }
829 | COLONCOLON identifier_path_for_expr
830 { $$ = parser->crate_name ($2); }
831 | KW_EXTERN identifier_path_for_expr
833 /* This is a gdb extension to make it possible to
834 refer to items in other crates. It just bypasses
835 adding the current crate to the front of the
837 $$ = parser->ast_path (parser->concat3 ("::",
844 identifier_path_for_expr:
846 { $$ = parser->ast_path ($1, NULL); }
847 | identifier_path_for_expr COLONCOLON IDENT
849 $$ = parser->ast_path (parser->concat3 ($1->left.sval.ptr,
853 | identifier_path_for_expr COLONCOLON '<' type_list '>'
854 { $$ = parser->ast_path ($1->left.sval, $4); }
855 | identifier_path_for_expr COLONCOLON '<' type_list RSH
857 $$ = parser->ast_path ($1->left.sval, $4);
858 rust_push_back ('>');
863 identifier_path_for_type
864 | KW_SELF COLONCOLON identifier_path_for_type
865 { $$ = parser->super_name ($3, 0); }
866 | maybe_self_path super_path identifier_path_for_type
867 { $$ = parser->super_name ($3, $2); }
868 | COLONCOLON identifier_path_for_type
869 { $$ = parser->crate_name ($2); }
870 | KW_EXTERN identifier_path_for_type
872 /* This is a gdb extension to make it possible to
873 refer to items in other crates. It just bypasses
874 adding the current crate to the front of the
876 $$ = parser->ast_path (parser->concat3 ("::",
883 just_identifiers_for_type:
885 { $$ = parser->ast_path ($1, NULL); }
886 | just_identifiers_for_type COLONCOLON IDENT
888 $$ = parser->ast_path (parser->concat3 ($1->left.sval.ptr,
894 identifier_path_for_type:
895 just_identifiers_for_type
896 | just_identifiers_for_type '<' type_list '>'
897 { $$ = parser->ast_path ($1->left.sval, $3); }
898 | just_identifiers_for_type '<' type_list RSH
900 $$ = parser->ast_path ($1->left.sval, $3);
901 rust_push_back ('>');
907 | '[' type ';' INTEGER ']'
908 { $$ = parser->ast_array_type ($2, $4); }
909 | '[' type ';' DECIMAL_INTEGER ']'
910 { $$ = parser->ast_array_type ($2, $4); }
912 { $$ = parser->ast_slice_type ($3); }
914 { $$ = parser->ast_reference_type ($2); }
916 { $$ = parser->ast_pointer_type ($3, 1); }
918 { $$ = parser->ast_pointer_type ($3, 0); }
919 | KW_FN '(' maybe_type_list ')' ARROW type
920 { $$ = parser->ast_function_type ($6, $3); }
921 | '(' maybe_type_list ')'
922 { $$ = parser->ast_tuple_type ($2); }
935 rust_op_vector *result = parser->new_op_vector ();
936 result->push_back ($1);
948 /* A struct of this type is used to describe a token. */
954 enum exp_opcode opcode;
957 /* Identifier tokens. */
959 static const struct token_info identifier_tokens[] =
961 { "as", KW_AS, OP_NULL },
962 { "false", KW_FALSE, OP_NULL },
963 { "if", 0, OP_NULL },
964 { "mut", KW_MUT, OP_NULL },
965 { "const", KW_CONST, OP_NULL },
966 { "self", KW_SELF, OP_NULL },
967 { "super", KW_SUPER, OP_NULL },
968 { "true", KW_TRUE, OP_NULL },
969 { "extern", KW_EXTERN, OP_NULL },
970 { "fn", KW_FN, OP_NULL },
971 { "sizeof", KW_SIZEOF, OP_NULL },
974 /* Operator tokens, sorted longest first. */
976 static const struct token_info operator_tokens[] =
978 { ">>=", COMPOUND_ASSIGN, BINOP_RSH },
979 { "<<=", COMPOUND_ASSIGN, BINOP_LSH },
981 { "<<", LSH, OP_NULL },
982 { ">>", RSH, OP_NULL },
983 { "&&", ANDAND, OP_NULL },
984 { "||", OROR, OP_NULL },
985 { "==", EQEQ, OP_NULL },
986 { "!=", NOTEQ, OP_NULL },
987 { "<=", LTEQ, OP_NULL },
988 { ">=", GTEQ, OP_NULL },
989 { "+=", COMPOUND_ASSIGN, BINOP_ADD },
990 { "-=", COMPOUND_ASSIGN, BINOP_SUB },
991 { "*=", COMPOUND_ASSIGN, BINOP_MUL },
992 { "/=", COMPOUND_ASSIGN, BINOP_DIV },
993 { "%=", COMPOUND_ASSIGN, BINOP_REM },
994 { "&=", COMPOUND_ASSIGN, BINOP_BITWISE_AND },
995 { "|=", COMPOUND_ASSIGN, BINOP_BITWISE_IOR },
996 { "^=", COMPOUND_ASSIGN, BINOP_BITWISE_XOR },
997 { "..=", DOTDOTEQ, OP_NULL },
999 { "::", COLONCOLON, OP_NULL },
1000 { "..", DOTDOT, OP_NULL },
1001 { "->", ARROW, OP_NULL }
1004 /* Helper function to copy to the name obstack. */
1007 rust_parser::copy_name (const char *name, int len)
1009 return (const char *) obstack_copy0 (&obstack, name, len);
1012 /* Helper function to make an stoken from a C string. */
1014 static struct stoken
1015 make_stoken (const char *p)
1017 struct stoken result;
1020 result.length = strlen (result.ptr);
1024 /* Helper function to concatenate three strings on the name
1028 rust_parser::concat3 (const char *s1, const char *s2, const char *s3)
1030 return make_stoken (obconcat (&obstack, s1, s2, s3, (char *) NULL));
1033 /* Return an AST node referring to NAME, but relative to the crate's
1036 const struct rust_op *
1037 rust_parser::crate_name (const struct rust_op *name)
1039 std::string crate = rust_crate_for_block (pstate->expression_context_block);
1040 struct stoken result;
1042 gdb_assert (name->opcode == OP_VAR_VALUE);
1045 error (_("Could not find crate for current location"));
1046 result = make_stoken (obconcat (&obstack, "::", crate.c_str (), "::",
1047 name->left.sval.ptr, (char *) NULL));
1049 return ast_path (result, name->right.params);
1052 /* Create an AST node referring to a "super::" qualified name. IDENT
1053 is the base name and N_SUPERS is how many "super::"s were
1054 provided. N_SUPERS can be zero. */
1056 const struct rust_op *
1057 rust_parser::super_name (const struct rust_op *ident, unsigned int n_supers)
1059 const char *scope = block_scope (pstate->expression_context_block);
1062 gdb_assert (ident->opcode == OP_VAR_VALUE);
1064 if (scope[0] == '\0')
1065 error (_("Couldn't find namespace scope for self::"));
1070 std::vector<int> offsets;
1071 unsigned int current_len;
1073 current_len = cp_find_first_component (scope);
1074 while (scope[current_len] != '\0')
1076 offsets.push_back (current_len);
1077 gdb_assert (scope[current_len] == ':');
1080 current_len += cp_find_first_component (scope
1084 len = offsets.size ();
1085 if (n_supers >= len)
1086 error (_("Too many super:: uses from '%s'"), scope);
1088 offset = offsets[len - n_supers];
1091 offset = strlen (scope);
1093 obstack_grow (&obstack, "::", 2);
1094 obstack_grow (&obstack, scope, offset);
1095 obstack_grow (&obstack, "::", 2);
1096 obstack_grow0 (&obstack, ident->left.sval.ptr, ident->left.sval.length);
1098 return ast_path (make_stoken ((const char *) obstack_finish (&obstack)),
1099 ident->right.params);
1102 /* A helper that updates the innermost block as appropriate. */
1105 update_innermost_block (struct block_symbol sym)
1107 if (symbol_read_needs_frame (sym.symbol))
1108 innermost_block.update (sym);
1111 /* Lex a hex number with at least MIN digits and at most MAX
1115 lex_hex (int min, int max)
1117 uint32_t result = 0;
1119 /* We only want to stop at MAX if we're lexing a byte escape. */
1120 int check_max = min == max;
1122 while ((check_max ? len <= max : 1)
1123 && ((lexptr[0] >= 'a' && lexptr[0] <= 'f')
1124 || (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1125 || (lexptr[0] >= '0' && lexptr[0] <= '9')))
1128 if (lexptr[0] >= 'a' && lexptr[0] <= 'f')
1129 result = result + 10 + lexptr[0] - 'a';
1130 else if (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1131 result = result + 10 + lexptr[0] - 'A';
1133 result = result + lexptr[0] - '0';
1139 error (_("Not enough hex digits seen"));
1142 gdb_assert (min != max);
1143 error (_("Overlong hex escape"));
1149 /* Lex an escape. IS_BYTE is true if we're lexing a byte escape;
1150 otherwise we're lexing a character escape. */
1153 lex_escape (int is_byte)
1157 gdb_assert (lexptr[0] == '\\');
1163 result = lex_hex (2, 2);
1168 error (_("Unicode escape in byte literal"));
1170 if (lexptr[0] != '{')
1171 error (_("Missing '{' in Unicode escape"));
1173 result = lex_hex (1, 6);
1174 /* Could do range checks here. */
1175 if (lexptr[0] != '}')
1176 error (_("Missing '}' in Unicode escape"));
1210 error (_("Invalid escape \\%c in literal"), lexptr[0]);
1216 /* Lex a character constant. */
1219 rust_parser::lex_character (YYSTYPE *lvalp)
1224 if (lexptr[0] == 'b')
1229 gdb_assert (lexptr[0] == '\'');
1231 /* This should handle UTF-8 here. */
1232 if (lexptr[0] == '\\')
1233 value = lex_escape (is_byte);
1236 value = lexptr[0] & 0xff;
1240 if (lexptr[0] != '\'')
1241 error (_("Unterminated character literal"));
1244 lvalp->typed_val_int.val = value;
1245 lvalp->typed_val_int.type = get_type (is_byte ? "u8" : "char");
1250 /* Return the offset of the double quote if STR looks like the start
1251 of a raw string, or 0 if STR does not start a raw string. */
1254 starts_raw_string (const char *str)
1256 const char *save = str;
1261 while (str[0] == '#')
1268 /* Return true if STR looks like the end of a raw string that had N
1269 hashes at the start. */
1272 ends_raw_string (const char *str, int n)
1276 gdb_assert (str[0] == '"');
1277 for (i = 0; i < n; ++i)
1278 if (str[i + 1] != '#')
1283 /* Lex a string constant. */
1286 rust_parser::lex_string (YYSTYPE *lvalp)
1288 int is_byte = lexptr[0] == 'b';
1293 raw_length = starts_raw_string (lexptr);
1294 lexptr += raw_length;
1295 gdb_assert (lexptr[0] == '"');
1304 if (lexptr[0] == '"' && ends_raw_string (lexptr, raw_length - 1))
1306 /* Exit with lexptr pointing after the final "#". */
1307 lexptr += raw_length;
1310 else if (lexptr[0] == '\0')
1311 error (_("Unexpected EOF in string"));
1313 value = lexptr[0] & 0xff;
1314 if (is_byte && value > 127)
1315 error (_("Non-ASCII value in raw byte string"));
1316 obstack_1grow (&obstack, value);
1320 else if (lexptr[0] == '"')
1322 /* Make sure to skip the quote. */
1326 else if (lexptr[0] == '\\')
1328 value = lex_escape (is_byte);
1331 obstack_1grow (&obstack, value);
1333 convert_between_encodings ("UTF-32", "UTF-8", (gdb_byte *) &value,
1334 sizeof (value), sizeof (value),
1335 &obstack, translit_none);
1337 else if (lexptr[0] == '\0')
1338 error (_("Unexpected EOF in string"));
1341 value = lexptr[0] & 0xff;
1342 if (is_byte && value > 127)
1343 error (_("Non-ASCII value in byte string"));
1344 obstack_1grow (&obstack, value);
1349 lvalp->sval.length = obstack_object_size (&obstack);
1350 lvalp->sval.ptr = (const char *) obstack_finish (&obstack);
1351 return is_byte ? BYTESTRING : STRING;
1354 /* Return true if STRING starts with whitespace followed by a digit. */
1357 space_then_number (const char *string)
1359 const char *p = string;
1361 while (p[0] == ' ' || p[0] == '\t')
1366 return *p >= '0' && *p <= '9';
1369 /* Return true if C can start an identifier. */
1372 rust_identifier_start_p (char c)
1374 return ((c >= 'a' && c <= 'z')
1375 || (c >= 'A' && c <= 'Z')
1380 /* Lex an identifier. */
1383 rust_parser::lex_identifier (YYSTYPE *lvalp)
1385 const char *start = lexptr;
1386 unsigned int length;
1387 const struct token_info *token;
1389 int is_gdb_var = lexptr[0] == '$';
1391 gdb_assert (rust_identifier_start_p (lexptr[0]));
1395 /* For the time being this doesn't handle Unicode rules. Non-ASCII
1396 identifiers are gated anyway. */
1397 while ((lexptr[0] >= 'a' && lexptr[0] <= 'z')
1398 || (lexptr[0] >= 'A' && lexptr[0] <= 'Z')
1400 || (is_gdb_var && lexptr[0] == '$')
1401 || (lexptr[0] >= '0' && lexptr[0] <= '9'))
1405 length = lexptr - start;
1407 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
1409 if (length == strlen (identifier_tokens[i].name)
1410 && strncmp (identifier_tokens[i].name, start, length) == 0)
1412 token = &identifier_tokens[i];
1419 if (token->value == 0)
1421 /* Leave the terminating token alone. */
1426 else if (token == NULL
1427 && (strncmp (start, "thread", length) == 0
1428 || strncmp (start, "task", length) == 0)
1429 && space_then_number (lexptr))
1431 /* "task" or "thread" followed by a number terminates the
1432 parse, per gdb rules. */
1437 if (token == NULL || (parse_completion && lexptr[0] == '\0'))
1438 lvalp->sval = make_stoken (copy_name (start, length));
1440 if (parse_completion && lexptr[0] == '\0')
1442 /* Prevent rustyylex from returning two COMPLETE tokens. */
1443 prev_lexptr = lexptr;
1448 return token->value;
1454 /* Lex an operator. */
1457 lex_operator (YYSTYPE *lvalp)
1459 const struct token_info *token = NULL;
1462 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
1464 if (strncmp (operator_tokens[i].name, lexptr,
1465 strlen (operator_tokens[i].name)) == 0)
1467 lexptr += strlen (operator_tokens[i].name);
1468 token = &operator_tokens[i];
1475 lvalp->opcode = token->opcode;
1476 return token->value;
1485 rust_parser::lex_number (YYSTYPE *lvalp)
1487 regmatch_t subexps[NUM_SUBEXPRESSIONS];
1490 int could_be_decimal = 1;
1491 int implicit_i32 = 0;
1492 const char *type_name = NULL;
1495 int type_index = -1;
1498 match = regexec (&number_regex, lexptr, ARRAY_SIZE (subexps), subexps, 0);
1499 /* Failure means the regexp is broken. */
1500 gdb_assert (match == 0);
1502 if (subexps[INT_TEXT].rm_so != -1)
1504 /* Integer part matched. */
1506 end_index = subexps[INT_TEXT].rm_eo;
1507 if (subexps[INT_TYPE].rm_so == -1)
1514 type_index = INT_TYPE;
1515 could_be_decimal = 0;
1518 else if (subexps[FLOAT_TYPE1].rm_so != -1)
1520 /* Found floating point type suffix. */
1521 end_index = subexps[FLOAT_TYPE1].rm_so;
1522 type_index = FLOAT_TYPE1;
1524 else if (subexps[FLOAT_TYPE2].rm_so != -1)
1526 /* Found floating point type suffix. */
1527 end_index = subexps[FLOAT_TYPE2].rm_so;
1528 type_index = FLOAT_TYPE2;
1532 /* Any other floating point match. */
1533 end_index = subexps[0].rm_eo;
1537 /* We need a special case if the final character is ".". In this
1538 case we might need to parse an integer. For example, "23.f()" is
1539 a request for a trait method call, not a syntax error involving
1540 the floating point number "23.". */
1541 gdb_assert (subexps[0].rm_eo > 0);
1542 if (lexptr[subexps[0].rm_eo - 1] == '.')
1544 const char *next = skip_spaces (&lexptr[subexps[0].rm_eo]);
1546 if (rust_identifier_start_p (*next) || *next == '.')
1550 end_index = subexps[0].rm_eo;
1552 could_be_decimal = 1;
1557 /* Compute the type name if we haven't already. */
1558 std::string type_name_holder;
1559 if (type_name == NULL)
1561 gdb_assert (type_index != -1);
1562 type_name_holder = std::string (lexptr + subexps[type_index].rm_so,
1563 (subexps[type_index].rm_eo
1564 - subexps[type_index].rm_so));
1565 type_name = type_name_holder.c_str ();
1568 /* Look up the type. */
1569 type = get_type (type_name);
1571 /* Copy the text of the number and remove the "_"s. */
1573 for (i = 0; i < end_index && lexptr[i]; ++i)
1575 if (lexptr[i] == '_')
1576 could_be_decimal = 0;
1578 number.push_back (lexptr[i]);
1581 /* Advance past the match. */
1582 lexptr += subexps[0].rm_eo;
1584 /* Parse the number. */
1591 if (number[0] == '0')
1593 if (number[1] == 'x')
1595 else if (number[1] == 'o')
1597 else if (number[1] == 'b')
1602 could_be_decimal = 0;
1606 value = strtoul (number.c_str () + offset, NULL, radix);
1607 if (implicit_i32 && value >= ((uint64_t) 1) << 31)
1608 type = get_type ("i64");
1610 lvalp->typed_val_int.val = value;
1611 lvalp->typed_val_int.type = type;
1615 lvalp->typed_val_float.type = type;
1616 bool parsed = parse_float (number.c_str (), number.length (),
1617 lvalp->typed_val_float.type,
1618 lvalp->typed_val_float.val);
1619 gdb_assert (parsed);
1622 return is_integer ? (could_be_decimal ? DECIMAL_INTEGER : INTEGER) : FLOAT;
1628 rustyylex (YYSTYPE *lvalp, rust_parser *parser)
1630 /* Skip all leading whitespace. */
1631 while (lexptr[0] == ' ' || lexptr[0] == '\t' || lexptr[0] == '\r'
1632 || lexptr[0] == '\n')
1635 /* If we hit EOF and we're completing, then return COMPLETE -- maybe
1636 we're completing an empty string at the end of a field_expr.
1637 But, we don't want to return two COMPLETE tokens in a row. */
1638 if (lexptr[0] == '\0' && lexptr == prev_lexptr)
1640 prev_lexptr = lexptr;
1641 if (lexptr[0] == '\0')
1643 if (parse_completion)
1645 lvalp->sval = make_stoken ("");
1651 if (lexptr[0] >= '0' && lexptr[0] <= '9')
1652 return parser->lex_number (lvalp);
1653 else if (lexptr[0] == 'b' && lexptr[1] == '\'')
1654 return parser->lex_character (lvalp);
1655 else if (lexptr[0] == 'b' && lexptr[1] == '"')
1656 return parser->lex_string (lvalp);
1657 else if (lexptr[0] == 'b' && starts_raw_string (lexptr + 1))
1658 return parser->lex_string (lvalp);
1659 else if (starts_raw_string (lexptr))
1660 return parser->lex_string (lvalp);
1661 else if (rust_identifier_start_p (lexptr[0]))
1662 return parser->lex_identifier (lvalp);
1663 else if (lexptr[0] == '"')
1664 return parser->lex_string (lvalp);
1665 else if (lexptr[0] == '\'')
1666 return parser->lex_character (lvalp);
1667 else if (lexptr[0] == '}' || lexptr[0] == ']')
1669 /* Falls through to lex_operator. */
1670 --parser->paren_depth;
1672 else if (lexptr[0] == '(' || lexptr[0] == '{')
1674 /* Falls through to lex_operator. */
1675 ++parser->paren_depth;
1677 else if (lexptr[0] == ',' && parser->pstate->comma_terminates
1678 && parser->paren_depth == 0)
1681 return lex_operator (lvalp);
1684 /* Push back a single character to be re-lexed. */
1687 rust_push_back (char c)
1689 /* Can't be called before any lexing. */
1690 gdb_assert (prev_lexptr != NULL);
1693 gdb_assert (*lexptr == c);
1698 /* Make an arbitrary operation and fill in the fields. */
1700 const struct rust_op *
1701 rust_parser::ast_operation (enum exp_opcode opcode, const struct rust_op *left,
1702 const struct rust_op *right)
1704 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1706 result->opcode = opcode;
1707 result->left.op = left;
1708 result->right.op = right;
1713 /* Make a compound assignment operation. */
1715 const struct rust_op *
1716 rust_parser::ast_compound_assignment (enum exp_opcode opcode,
1717 const struct rust_op *left,
1718 const struct rust_op *right)
1720 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1722 result->opcode = opcode;
1723 result->compound_assignment = 1;
1724 result->left.op = left;
1725 result->right.op = right;
1730 /* Make a typed integer literal operation. */
1732 const struct rust_op *
1733 rust_parser::ast_literal (struct typed_val_int val)
1735 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1737 result->opcode = OP_LONG;
1738 result->left.typed_val_int = val;
1743 /* Make a typed floating point literal operation. */
1745 const struct rust_op *
1746 rust_parser::ast_dliteral (struct typed_val_float val)
1748 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1750 result->opcode = OP_FLOAT;
1751 result->left.typed_val_float = val;
1756 /* Make a unary operation. */
1758 const struct rust_op *
1759 rust_parser::ast_unary (enum exp_opcode opcode, const struct rust_op *expr)
1761 return ast_operation (opcode, expr, NULL);
1764 /* Make a cast operation. */
1766 const struct rust_op *
1767 rust_parser::ast_cast (const struct rust_op *expr, const struct rust_op *type)
1769 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1771 result->opcode = UNOP_CAST;
1772 result->left.op = expr;
1773 result->right.op = type;
1778 /* Make a call-like operation. This is nominally a function call, but
1779 when lowering we may discover that it actually represents the
1780 creation of a tuple struct. */
1782 const struct rust_op *
1783 rust_parser::ast_call_ish (enum exp_opcode opcode, const struct rust_op *expr,
1784 rust_op_vector *params)
1786 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1788 result->opcode = opcode;
1789 result->left.op = expr;
1790 result->right.params = params;
1795 /* Make a structure creation operation. */
1797 const struct rust_op *
1798 rust_parser::ast_struct (const struct rust_op *name, rust_set_vector *fields)
1800 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1802 result->opcode = OP_AGGREGATE;
1803 result->left.op = name;
1804 result->right.field_inits = fields;
1809 /* Make an identifier path. */
1811 const struct rust_op *
1812 rust_parser::ast_path (struct stoken path, rust_op_vector *params)
1814 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1816 result->opcode = OP_VAR_VALUE;
1817 result->left.sval = path;
1818 result->right.params = params;
1823 /* Make a string constant operation. */
1825 const struct rust_op *
1826 rust_parser::ast_string (struct stoken str)
1828 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1830 result->opcode = OP_STRING;
1831 result->left.sval = str;
1836 /* Make a field expression. */
1838 const struct rust_op *
1839 rust_parser::ast_structop (const struct rust_op *left, const char *name,
1842 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1844 result->opcode = STRUCTOP_STRUCT;
1845 result->completing = completing;
1846 result->left.op = left;
1847 result->right.sval = make_stoken (name);
1852 /* Make an anonymous struct operation, like 'x.0'. */
1854 const struct rust_op *
1855 rust_parser::ast_structop_anonymous (const struct rust_op *left,
1856 struct typed_val_int number)
1858 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1860 result->opcode = STRUCTOP_ANONYMOUS;
1861 result->left.op = left;
1862 result->right.typed_val_int = number;
1867 /* Make a range operation. */
1869 const struct rust_op *
1870 rust_parser::ast_range (const struct rust_op *lhs, const struct rust_op *rhs,
1873 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1875 result->opcode = OP_RANGE;
1876 result->inclusive = inclusive;
1877 result->left.op = lhs;
1878 result->right.op = rhs;
1883 /* A helper function to make a type-related AST node. */
1886 rust_parser::ast_basic_type (enum type_code typecode)
1888 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1890 result->opcode = OP_TYPE;
1891 result->typecode = typecode;
1895 /* Create an AST node describing an array type. */
1897 const struct rust_op *
1898 rust_parser::ast_array_type (const struct rust_op *lhs,
1899 struct typed_val_int val)
1901 struct rust_op *result = ast_basic_type (TYPE_CODE_ARRAY);
1903 result->left.op = lhs;
1904 result->right.typed_val_int = val;
1908 /* Create an AST node describing a reference type. */
1910 const struct rust_op *
1911 rust_parser::ast_slice_type (const struct rust_op *type)
1913 /* Use TYPE_CODE_COMPLEX just because it is handy. */
1914 struct rust_op *result = ast_basic_type (TYPE_CODE_COMPLEX);
1916 result->left.op = type;
1920 /* Create an AST node describing a reference type. */
1922 const struct rust_op *
1923 rust_parser::ast_reference_type (const struct rust_op *type)
1925 struct rust_op *result = ast_basic_type (TYPE_CODE_REF);
1927 result->left.op = type;
1931 /* Create an AST node describing a pointer type. */
1933 const struct rust_op *
1934 rust_parser::ast_pointer_type (const struct rust_op *type, int is_mut)
1936 struct rust_op *result = ast_basic_type (TYPE_CODE_PTR);
1938 result->left.op = type;
1939 /* For the time being we ignore is_mut. */
1943 /* Create an AST node describing a function type. */
1945 const struct rust_op *
1946 rust_parser::ast_function_type (const struct rust_op *rtype,
1947 rust_op_vector *params)
1949 struct rust_op *result = ast_basic_type (TYPE_CODE_FUNC);
1951 result->left.op = rtype;
1952 result->right.params = params;
1956 /* Create an AST node describing a tuple type. */
1958 const struct rust_op *
1959 rust_parser::ast_tuple_type (rust_op_vector *params)
1961 struct rust_op *result = ast_basic_type (TYPE_CODE_STRUCT);
1963 result->left.params = params;
1967 /* A helper to appropriately munge NAME and BLOCK depending on the
1968 presence of a leading "::". */
1971 munge_name_and_block (const char **name, const struct block **block)
1973 /* If it is a global reference, skip the current block in favor of
1974 the static block. */
1975 if (strncmp (*name, "::", 2) == 0)
1978 *block = block_static_block (*block);
1982 /* Like lookup_symbol, but handles Rust namespace conventions, and
1983 doesn't require field_of_this_result. */
1985 static struct block_symbol
1986 rust_lookup_symbol (const char *name, const struct block *block,
1987 const domain_enum domain)
1989 struct block_symbol result;
1991 munge_name_and_block (&name, &block);
1993 result = lookup_symbol (name, block, domain, NULL);
1994 if (result.symbol != NULL)
1995 update_innermost_block (result);
1999 /* Look up a type, following Rust namespace conventions. */
2002 rust_parser::rust_lookup_type (const char *name, const struct block *block)
2004 struct block_symbol result;
2007 munge_name_and_block (&name, &block);
2009 result = lookup_symbol (name, block, STRUCT_DOMAIN, NULL);
2010 if (result.symbol != NULL)
2012 update_innermost_block (result);
2013 return SYMBOL_TYPE (result.symbol);
2016 type = lookup_typename (language (), arch (), name, NULL, 1);
2020 /* Last chance, try a built-in type. */
2021 return language_lookup_primitive_type (language (), arch (), name);
2024 /* Convert a vector of rust_ops representing types to a vector of
2027 std::vector<struct type *>
2028 rust_parser::convert_params_to_types (rust_op_vector *params)
2030 std::vector<struct type *> result;
2032 if (params != nullptr)
2034 for (const rust_op *op : *params)
2035 result.push_back (convert_ast_to_type (op));
2041 /* Convert a rust_op representing a type to a struct type *. */
2044 rust_parser::convert_ast_to_type (const struct rust_op *operation)
2046 struct type *type, *result = NULL;
2048 if (operation->opcode == OP_VAR_VALUE)
2050 const char *varname = convert_name (operation);
2052 result = rust_lookup_type (varname, pstate->expression_context_block);
2054 error (_("No typed name '%s' in current context"), varname);
2058 gdb_assert (operation->opcode == OP_TYPE);
2060 switch (operation->typecode)
2062 case TYPE_CODE_ARRAY:
2063 type = convert_ast_to_type (operation->left.op);
2064 if (operation->right.typed_val_int.val < 0)
2065 error (_("Negative array length"));
2066 result = lookup_array_range_type (type, 0,
2067 operation->right.typed_val_int.val - 1);
2070 case TYPE_CODE_COMPLEX:
2072 struct type *usize = get_type ("usize");
2074 type = convert_ast_to_type (operation->left.op);
2075 result = rust_slice_type ("&[*gdb*]", type, usize);
2081 /* For now we treat &x and *x identically. */
2082 type = convert_ast_to_type (operation->left.op);
2083 result = lookup_pointer_type (type);
2086 case TYPE_CODE_FUNC:
2088 std::vector<struct type *> args
2089 (convert_params_to_types (operation->right.params));
2090 struct type **argtypes = NULL;
2092 type = convert_ast_to_type (operation->left.op);
2094 argtypes = args.data ();
2097 = lookup_function_type_with_arguments (type, args.size (),
2099 result = lookup_pointer_type (result);
2103 case TYPE_CODE_STRUCT:
2105 std::vector<struct type *> args
2106 (convert_params_to_types (operation->left.params));
2110 obstack_1grow (&obstack, '(');
2111 for (i = 0; i < args.size (); ++i)
2113 std::string type_name = type_to_string (args[i]);
2116 obstack_1grow (&obstack, ',');
2117 obstack_grow_str (&obstack, type_name.c_str ());
2120 obstack_grow_str0 (&obstack, ")");
2121 name = (const char *) obstack_finish (&obstack);
2123 /* We don't allow creating new tuple types (yet), but we do
2124 allow looking up existing tuple types. */
2125 result = rust_lookup_type (name, pstate->expression_context_block);
2127 error (_("could not find tuple type '%s'"), name);
2132 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_type");
2135 gdb_assert (result != NULL);
2139 /* A helper function to turn a rust_op representing a name into a full
2140 name. This applies generic arguments as needed. The returned name
2141 is allocated on the work obstack. */
2144 rust_parser::convert_name (const struct rust_op *operation)
2148 gdb_assert (operation->opcode == OP_VAR_VALUE);
2150 if (operation->right.params == NULL)
2151 return operation->left.sval.ptr;
2153 std::vector<struct type *> types
2154 (convert_params_to_types (operation->right.params));
2156 obstack_grow_str (&obstack, operation->left.sval.ptr);
2157 obstack_1grow (&obstack, '<');
2158 for (i = 0; i < types.size (); ++i)
2160 std::string type_name = type_to_string (types[i]);
2163 obstack_1grow (&obstack, ',');
2165 obstack_grow_str (&obstack, type_name.c_str ());
2167 obstack_grow_str0 (&obstack, ">");
2169 return (const char *) obstack_finish (&obstack);
2172 /* A helper function that converts a vec of rust_ops to a gdb
2176 rust_parser::convert_params_to_expression (rust_op_vector *params,
2177 const struct rust_op *top)
2179 for (const rust_op *elem : *params)
2180 convert_ast_to_expression (elem, top);
2183 /* Lower a rust_op to a gdb expression. STATE is the parser state.
2184 OPERATION is the operation to lower. TOP is a pointer to the
2185 top-most operation; it is used to handle the special case where the
2186 top-most expression is an identifier and can be optionally lowered
2187 to OP_TYPE. WANT_TYPE is a flag indicating that, if the expression
2188 is the name of a type, then emit an OP_TYPE for it (rather than
2189 erroring). If WANT_TYPE is set, then the similar TOP handling is
2193 rust_parser::convert_ast_to_expression (const struct rust_op *operation,
2194 const struct rust_op *top,
2197 switch (operation->opcode)
2200 write_exp_elt_opcode (pstate, OP_LONG);
2201 write_exp_elt_type (pstate, operation->left.typed_val_int.type);
2202 write_exp_elt_longcst (pstate, operation->left.typed_val_int.val);
2203 write_exp_elt_opcode (pstate, OP_LONG);
2207 write_exp_elt_opcode (pstate, OP_FLOAT);
2208 write_exp_elt_type (pstate, operation->left.typed_val_float.type);
2209 write_exp_elt_floatcst (pstate, operation->left.typed_val_float.val);
2210 write_exp_elt_opcode (pstate, OP_FLOAT);
2213 case STRUCTOP_STRUCT:
2215 convert_ast_to_expression (operation->left.op, top);
2217 if (operation->completing)
2218 mark_struct_expression (pstate);
2219 write_exp_elt_opcode (pstate, STRUCTOP_STRUCT);
2220 write_exp_string (pstate, operation->right.sval);
2221 write_exp_elt_opcode (pstate, STRUCTOP_STRUCT);
2225 case STRUCTOP_ANONYMOUS:
2227 convert_ast_to_expression (operation->left.op, top);
2229 write_exp_elt_opcode (pstate, STRUCTOP_ANONYMOUS);
2230 write_exp_elt_longcst (pstate, operation->right.typed_val_int.val);
2231 write_exp_elt_opcode (pstate, STRUCTOP_ANONYMOUS);
2236 convert_ast_to_expression (operation->left.op, top, true);
2237 write_exp_elt_opcode (pstate, UNOP_SIZEOF);
2242 case UNOP_COMPLEMENT:
2245 convert_ast_to_expression (operation->left.op, top);
2246 write_exp_elt_opcode (pstate, operation->opcode);
2249 case BINOP_SUBSCRIPT:
2256 case BINOP_BITWISE_AND:
2257 case BINOP_BITWISE_IOR:
2258 case BINOP_BITWISE_XOR:
2261 case BINOP_LOGICAL_OR:
2262 case BINOP_LOGICAL_AND:
2264 case BINOP_NOTEQUAL:
2271 convert_ast_to_expression (operation->left.op, top);
2272 convert_ast_to_expression (operation->right.op, top);
2273 if (operation->compound_assignment)
2275 write_exp_elt_opcode (pstate, BINOP_ASSIGN_MODIFY);
2276 write_exp_elt_opcode (pstate, operation->opcode);
2277 write_exp_elt_opcode (pstate, BINOP_ASSIGN_MODIFY);
2280 write_exp_elt_opcode (pstate, operation->opcode);
2282 if (operation->compound_assignment
2283 || operation->opcode == BINOP_ASSIGN)
2287 type = language_lookup_primitive_type (pstate->language (),
2291 write_exp_elt_opcode (pstate, OP_LONG);
2292 write_exp_elt_type (pstate, type);
2293 write_exp_elt_longcst (pstate, 0);
2294 write_exp_elt_opcode (pstate, OP_LONG);
2296 write_exp_elt_opcode (pstate, BINOP_COMMA);
2302 struct type *type = convert_ast_to_type (operation->right.op);
2304 convert_ast_to_expression (operation->left.op, top);
2305 write_exp_elt_opcode (pstate, UNOP_CAST);
2306 write_exp_elt_type (pstate, type);
2307 write_exp_elt_opcode (pstate, UNOP_CAST);
2313 if (operation->left.op->opcode == OP_VAR_VALUE)
2316 const char *varname = convert_name (operation->left.op);
2318 type = rust_lookup_type (varname,
2319 pstate->expression_context_block);
2322 /* This is actually a tuple struct expression, not a
2324 rust_op_vector *params = operation->right.params;
2326 if (TYPE_CODE (type) != TYPE_CODE_NAMESPACE)
2328 if (!rust_tuple_struct_type_p (type))
2329 error (_("Type %s is not a tuple struct"), varname);
2331 for (int i = 0; i < params->size (); ++i)
2333 char *cell = get_print_cell ();
2335 xsnprintf (cell, PRINT_CELL_SIZE, "__%d", i);
2336 write_exp_elt_opcode (pstate, OP_NAME);
2337 write_exp_string (pstate, make_stoken (cell));
2338 write_exp_elt_opcode (pstate, OP_NAME);
2340 convert_ast_to_expression ((*params)[i], top);
2343 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2344 write_exp_elt_type (pstate, type);
2345 write_exp_elt_longcst (pstate, 2 * params->size ());
2346 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2351 convert_ast_to_expression (operation->left.op, top);
2352 convert_params_to_expression (operation->right.params, top);
2353 write_exp_elt_opcode (pstate, OP_FUNCALL);
2354 write_exp_elt_longcst (pstate, operation->right.params->size ());
2355 write_exp_elt_longcst (pstate, OP_FUNCALL);
2360 gdb_assert (operation->left.op == NULL);
2361 convert_params_to_expression (operation->right.params, top);
2362 write_exp_elt_opcode (pstate, OP_ARRAY);
2363 write_exp_elt_longcst (pstate, 0);
2364 write_exp_elt_longcst (pstate, operation->right.params->size () - 1);
2365 write_exp_elt_longcst (pstate, OP_ARRAY);
2370 struct block_symbol sym;
2371 const char *varname;
2373 if (operation->left.sval.ptr[0] == '$')
2375 write_dollar_variable (pstate, operation->left.sval);
2379 varname = convert_name (operation);
2380 sym = rust_lookup_symbol (varname, pstate->expression_context_block,
2382 if (sym.symbol != NULL && SYMBOL_CLASS (sym.symbol) != LOC_TYPEDEF)
2384 write_exp_elt_opcode (pstate, OP_VAR_VALUE);
2385 write_exp_elt_block (pstate, sym.block);
2386 write_exp_elt_sym (pstate, sym.symbol);
2387 write_exp_elt_opcode (pstate, OP_VAR_VALUE);
2391 struct type *type = NULL;
2393 if (sym.symbol != NULL)
2395 gdb_assert (SYMBOL_CLASS (sym.symbol) == LOC_TYPEDEF);
2396 type = SYMBOL_TYPE (sym.symbol);
2399 type = rust_lookup_type (varname,
2400 pstate->expression_context_block);
2402 error (_("No symbol '%s' in current context"), varname);
2405 && TYPE_CODE (type) == TYPE_CODE_STRUCT
2406 && TYPE_NFIELDS (type) == 0)
2408 /* A unit-like struct. */
2409 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2410 write_exp_elt_type (pstate, type);
2411 write_exp_elt_longcst (pstate, 0);
2412 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2414 else if (want_type || operation == top)
2416 write_exp_elt_opcode (pstate, OP_TYPE);
2417 write_exp_elt_type (pstate, type);
2418 write_exp_elt_opcode (pstate, OP_TYPE);
2421 error (_("Found type '%s', which can't be "
2422 "evaluated in this context"),
2431 rust_set_vector *fields = operation->right.field_inits;
2436 for (const set_field &init : *fields)
2438 if (init.name.ptr != NULL)
2440 write_exp_elt_opcode (pstate, OP_NAME);
2441 write_exp_string (pstate, init.name);
2442 write_exp_elt_opcode (pstate, OP_NAME);
2446 convert_ast_to_expression (init.init, top);
2449 if (init.name.ptr == NULL)
2451 /* This is handled differently from Ada in our
2453 write_exp_elt_opcode (pstate, OP_OTHERS);
2457 name = convert_name (operation->left.op);
2458 type = rust_lookup_type (name, pstate->expression_context_block);
2460 error (_("Could not find type '%s'"), operation->left.sval.ptr);
2462 if (TYPE_CODE (type) != TYPE_CODE_STRUCT
2463 || rust_tuple_type_p (type)
2464 || rust_tuple_struct_type_p (type))
2465 error (_("Struct expression applied to non-struct type"));
2467 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2468 write_exp_elt_type (pstate, type);
2469 write_exp_elt_longcst (pstate, length);
2470 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2476 write_exp_elt_opcode (pstate, OP_STRING);
2477 write_exp_string (pstate, operation->left.sval);
2478 write_exp_elt_opcode (pstate, OP_STRING);
2484 enum range_type kind = BOTH_BOUND_DEFAULT;
2486 if (operation->left.op != NULL)
2488 convert_ast_to_expression (operation->left.op, top);
2489 kind = HIGH_BOUND_DEFAULT;
2491 if (operation->right.op != NULL)
2493 convert_ast_to_expression (operation->right.op, top);
2494 if (kind == BOTH_BOUND_DEFAULT)
2495 kind = (operation->inclusive
2496 ? LOW_BOUND_DEFAULT : LOW_BOUND_DEFAULT_EXCLUSIVE);
2499 gdb_assert (kind == HIGH_BOUND_DEFAULT);
2500 kind = (operation->inclusive
2501 ? NONE_BOUND_DEFAULT : NONE_BOUND_DEFAULT_EXCLUSIVE);
2506 /* Nothing should make an inclusive range without an upper
2508 gdb_assert (!operation->inclusive);
2511 write_exp_elt_opcode (pstate, OP_RANGE);
2512 write_exp_elt_longcst (pstate, kind);
2513 write_exp_elt_opcode (pstate, OP_RANGE);
2518 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_expression");
2524 /* The parser as exposed to gdb. */
2527 rust_parse (struct parser_state *state)
2531 /* This sets various globals and also clears them on
2533 rust_parser parser (state);
2535 result = rustyyparse (&parser);
2537 if (!result || (parse_completion && parser.rust_ast != NULL))
2538 parser.convert_ast_to_expression (parser.rust_ast, parser.rust_ast);
2543 /* The parser error handler. */
2546 rustyyerror (rust_parser *parser, const char *msg)
2548 const char *where = prev_lexptr ? prev_lexptr : lexptr;
2549 error (_("%s in expression, near `%s'."), msg, where);
2556 /* Initialize the lexer for testing. */
2559 rust_lex_test_init (rust_parser *parser, const char *input)
2563 parser->paren_depth = 0;
2566 /* A test helper that lexes a string, expecting a single token. It
2567 returns the lexer data for this token. */
2570 rust_lex_test_one (rust_parser *parser, const char *input, int expected)
2575 rust_lex_test_init (parser, input);
2577 token = rustyylex (&result, parser);
2578 SELF_CHECK (token == expected);
2583 token = rustyylex (&ignore, parser);
2584 SELF_CHECK (token == 0);
2590 /* Test that INPUT lexes as the integer VALUE. */
2593 rust_lex_int_test (rust_parser *parser, const char *input, int value, int kind)
2595 RUSTSTYPE result = rust_lex_test_one (parser, input, kind);
2596 SELF_CHECK (result.typed_val_int.val == value);
2599 /* Test that INPUT throws an exception with text ERR. */
2602 rust_lex_exception_test (rust_parser *parser, const char *input,
2607 /* The "kind" doesn't matter. */
2608 rust_lex_test_one (parser, input, DECIMAL_INTEGER);
2611 CATCH (except, RETURN_MASK_ERROR)
2613 SELF_CHECK (strcmp (except.message, err) == 0);
2618 /* Test that INPUT lexes as the identifier, string, or byte-string
2619 VALUE. KIND holds the expected token kind. */
2622 rust_lex_stringish_test (rust_parser *parser, const char *input,
2623 const char *value, int kind)
2625 RUSTSTYPE result = rust_lex_test_one (parser, input, kind);
2626 SELF_CHECK (result.sval.length == strlen (value));
2627 SELF_CHECK (strncmp (result.sval.ptr, value, result.sval.length) == 0);
2630 /* Helper to test that a string parses as a given token sequence. */
2633 rust_lex_test_sequence (rust_parser *parser, const char *input, int len,
2634 const int expected[])
2639 parser->paren_depth = 0;
2641 for (i = 0; i < len; ++i)
2644 int token = rustyylex (&ignore, parser);
2646 SELF_CHECK (token == expected[i]);
2650 /* Tests for an integer-parsing corner case. */
2653 rust_lex_test_trailing_dot (rust_parser *parser)
2655 const int expected1[] = { DECIMAL_INTEGER, '.', IDENT, '(', ')', 0 };
2656 const int expected2[] = { INTEGER, '.', IDENT, '(', ')', 0 };
2657 const int expected3[] = { FLOAT, EQEQ, '(', ')', 0 };
2658 const int expected4[] = { DECIMAL_INTEGER, DOTDOT, DECIMAL_INTEGER, 0 };
2660 rust_lex_test_sequence (parser, "23.g()", ARRAY_SIZE (expected1), expected1);
2661 rust_lex_test_sequence (parser, "23_0.g()", ARRAY_SIZE (expected2),
2663 rust_lex_test_sequence (parser, "23.==()", ARRAY_SIZE (expected3),
2665 rust_lex_test_sequence (parser, "23..25", ARRAY_SIZE (expected4), expected4);
2668 /* Tests of completion. */
2671 rust_lex_test_completion (rust_parser *parser)
2673 const int expected[] = { IDENT, '.', COMPLETE, 0 };
2675 parse_completion = 1;
2677 rust_lex_test_sequence (parser, "something.wha", ARRAY_SIZE (expected),
2679 rust_lex_test_sequence (parser, "something.", ARRAY_SIZE (expected),
2682 parse_completion = 0;
2685 /* Test pushback. */
2688 rust_lex_test_push_back (rust_parser *parser)
2693 rust_lex_test_init (parser, ">>=");
2695 token = rustyylex (&lval, parser);
2696 SELF_CHECK (token == COMPOUND_ASSIGN);
2697 SELF_CHECK (lval.opcode == BINOP_RSH);
2699 rust_push_back ('=');
2701 token = rustyylex (&lval, parser);
2702 SELF_CHECK (token == '=');
2704 token = rustyylex (&lval, parser);
2705 SELF_CHECK (token == 0);
2708 /* Unit test the lexer. */
2711 rust_lex_tests (void)
2715 // Set up dummy "parser", so that rust_type works.
2716 struct parser_state ps (&rust_language_defn, target_gdbarch (),
2718 rust_parser parser (&ps);
2720 rust_lex_test_one (&parser, "", 0);
2721 rust_lex_test_one (&parser, " \t \n \r ", 0);
2722 rust_lex_test_one (&parser, "thread 23", 0);
2723 rust_lex_test_one (&parser, "task 23", 0);
2724 rust_lex_test_one (&parser, "th 104", 0);
2725 rust_lex_test_one (&parser, "ta 97", 0);
2727 rust_lex_int_test (&parser, "'z'", 'z', INTEGER);
2728 rust_lex_int_test (&parser, "'\\xff'", 0xff, INTEGER);
2729 rust_lex_int_test (&parser, "'\\u{1016f}'", 0x1016f, INTEGER);
2730 rust_lex_int_test (&parser, "b'z'", 'z', INTEGER);
2731 rust_lex_int_test (&parser, "b'\\xfe'", 0xfe, INTEGER);
2732 rust_lex_int_test (&parser, "b'\\xFE'", 0xfe, INTEGER);
2733 rust_lex_int_test (&parser, "b'\\xfE'", 0xfe, INTEGER);
2735 /* Test all escapes in both modes. */
2736 rust_lex_int_test (&parser, "'\\n'", '\n', INTEGER);
2737 rust_lex_int_test (&parser, "'\\r'", '\r', INTEGER);
2738 rust_lex_int_test (&parser, "'\\t'", '\t', INTEGER);
2739 rust_lex_int_test (&parser, "'\\\\'", '\\', INTEGER);
2740 rust_lex_int_test (&parser, "'\\0'", '\0', INTEGER);
2741 rust_lex_int_test (&parser, "'\\''", '\'', INTEGER);
2742 rust_lex_int_test (&parser, "'\\\"'", '"', INTEGER);
2744 rust_lex_int_test (&parser, "b'\\n'", '\n', INTEGER);
2745 rust_lex_int_test (&parser, "b'\\r'", '\r', INTEGER);
2746 rust_lex_int_test (&parser, "b'\\t'", '\t', INTEGER);
2747 rust_lex_int_test (&parser, "b'\\\\'", '\\', INTEGER);
2748 rust_lex_int_test (&parser, "b'\\0'", '\0', INTEGER);
2749 rust_lex_int_test (&parser, "b'\\''", '\'', INTEGER);
2750 rust_lex_int_test (&parser, "b'\\\"'", '"', INTEGER);
2752 rust_lex_exception_test (&parser, "'z", "Unterminated character literal");
2753 rust_lex_exception_test (&parser, "b'\\x0'", "Not enough hex digits seen");
2754 rust_lex_exception_test (&parser, "b'\\u{0}'",
2755 "Unicode escape in byte literal");
2756 rust_lex_exception_test (&parser, "'\\x0'", "Not enough hex digits seen");
2757 rust_lex_exception_test (&parser, "'\\u0'", "Missing '{' in Unicode escape");
2758 rust_lex_exception_test (&parser, "'\\u{0", "Missing '}' in Unicode escape");
2759 rust_lex_exception_test (&parser, "'\\u{0000007}", "Overlong hex escape");
2760 rust_lex_exception_test (&parser, "'\\u{}", "Not enough hex digits seen");
2761 rust_lex_exception_test (&parser, "'\\Q'", "Invalid escape \\Q in literal");
2762 rust_lex_exception_test (&parser, "b'\\Q'", "Invalid escape \\Q in literal");
2764 rust_lex_int_test (&parser, "23", 23, DECIMAL_INTEGER);
2765 rust_lex_int_test (&parser, "2_344__29", 234429, INTEGER);
2766 rust_lex_int_test (&parser, "0x1f", 0x1f, INTEGER);
2767 rust_lex_int_test (&parser, "23usize", 23, INTEGER);
2768 rust_lex_int_test (&parser, "23i32", 23, INTEGER);
2769 rust_lex_int_test (&parser, "0x1_f", 0x1f, INTEGER);
2770 rust_lex_int_test (&parser, "0b1_101011__", 0x6b, INTEGER);
2771 rust_lex_int_test (&parser, "0o001177i64", 639, INTEGER);
2773 rust_lex_test_trailing_dot (&parser);
2775 rust_lex_test_one (&parser, "23.", FLOAT);
2776 rust_lex_test_one (&parser, "23.99f32", FLOAT);
2777 rust_lex_test_one (&parser, "23e7", FLOAT);
2778 rust_lex_test_one (&parser, "23E-7", FLOAT);
2779 rust_lex_test_one (&parser, "23e+7", FLOAT);
2780 rust_lex_test_one (&parser, "23.99e+7f64", FLOAT);
2781 rust_lex_test_one (&parser, "23.82f32", FLOAT);
2783 rust_lex_stringish_test (&parser, "hibob", "hibob", IDENT);
2784 rust_lex_stringish_test (&parser, "hibob__93", "hibob__93", IDENT);
2785 rust_lex_stringish_test (&parser, "thread", "thread", IDENT);
2787 rust_lex_stringish_test (&parser, "\"string\"", "string", STRING);
2788 rust_lex_stringish_test (&parser, "\"str\\ting\"", "str\ting", STRING);
2789 rust_lex_stringish_test (&parser, "\"str\\\"ing\"", "str\"ing", STRING);
2790 rust_lex_stringish_test (&parser, "r\"str\\ing\"", "str\\ing", STRING);
2791 rust_lex_stringish_test (&parser, "r#\"str\\ting\"#", "str\\ting", STRING);
2792 rust_lex_stringish_test (&parser, "r###\"str\\\"ing\"###", "str\\\"ing",
2795 rust_lex_stringish_test (&parser, "b\"string\"", "string", BYTESTRING);
2796 rust_lex_stringish_test (&parser, "b\"\x73tring\"", "string", BYTESTRING);
2797 rust_lex_stringish_test (&parser, "b\"str\\\"ing\"", "str\"ing", BYTESTRING);
2798 rust_lex_stringish_test (&parser, "br####\"\\x73tring\"####", "\\x73tring",
2801 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
2802 rust_lex_test_one (&parser, identifier_tokens[i].name,
2803 identifier_tokens[i].value);
2805 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
2806 rust_lex_test_one (&parser, operator_tokens[i].name,
2807 operator_tokens[i].value);
2809 rust_lex_test_completion (&parser);
2810 rust_lex_test_push_back (&parser);
2813 #endif /* GDB_SELF_TEST */
2816 _initialize_rust_exp (void)
2818 int code = regcomp (&number_regex, number_regex_text, REG_EXTENDED);
2819 /* If the regular expression was incorrect, it was a programming
2821 gdb_assert (code == 0);
2824 selftests::register_test ("rust-lex", rust_lex_tests);