1 /* Bison parser for Rust expressions, for GDB.
2 Copyright (C) 2016-2018 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"
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 const struct rust_op *str = parser->ast_string ($1);
587 struct set_field field;
588 struct typed_val_int val;
591 rust_set_vector *fields = parser->new_set_vector ();
593 /* Wrap the raw string in the &str struct. */
594 field.name.ptr = "data_ptr";
595 field.name.length = strlen (field.name.ptr);
596 field.init = parser->ast_unary (UNOP_ADDR,
597 parser->ast_string ($1));
598 fields->push_back (field);
600 val.type = parser->get_type ("usize");
603 field.name.ptr = "length";
604 field.name.length = strlen (field.name.ptr);
605 field.init = parser->ast_literal (val);
606 fields->push_back (field);
609 token.length = strlen (token.ptr);
610 $$ = parser->ast_struct (parser->ast_path (token, NULL),
614 { $$ = parser->ast_string ($1); }
617 struct typed_val_int val;
619 val.type = language_bool_type (parser->language (),
622 $$ = parser->ast_literal (val);
626 struct typed_val_int val;
628 val.type = language_bool_type (parser->language (),
631 $$ = parser->ast_literal (val);
637 { $$ = parser->ast_structop ($1, $3.ptr, 0); }
640 $$ = parser->ast_structop ($1, $3.ptr, 1);
641 parser->rust_ast = $$;
643 | expr '.' DECIMAL_INTEGER
644 { $$ = parser->ast_structop_anonymous ($1, $3); }
649 { $$ = parser->ast_operation (BINOP_SUBSCRIPT, $1, $3); }
654 { $$ = parser->ast_unary (UNOP_PLUS, $2); }
656 | '-' expr %prec UNARY
657 { $$ = parser->ast_unary (UNOP_NEG, $2); }
659 | '!' expr %prec UNARY
661 /* Note that we provide a Rust-specific evaluator
662 override for UNOP_COMPLEMENT, so it can do the
663 right thing for both bool and integral
665 $$ = parser->ast_unary (UNOP_COMPLEMENT, $2);
668 | '*' expr %prec UNARY
669 { $$ = parser->ast_unary (UNOP_IND, $2); }
671 | '&' expr %prec UNARY
672 { $$ = parser->ast_unary (UNOP_ADDR, $2); }
674 | '&' KW_MUT expr %prec UNARY
675 { $$ = parser->ast_unary (UNOP_ADDR, $3); }
676 | KW_SIZEOF '(' expr ')' %prec UNARY
677 { $$ = parser->ast_unary (UNOP_SIZEOF, $3); }
684 | compound_assignment_expr
689 { $$ = parser->ast_operation (BINOP_MUL, $1, $3); }
692 { $$ = parser->ast_operation (BINOP_REPEAT, $1, $3); }
695 { $$ = parser->ast_operation (BINOP_DIV, $1, $3); }
698 { $$ = parser->ast_operation (BINOP_REM, $1, $3); }
701 { $$ = parser->ast_operation (BINOP_LESS, $1, $3); }
704 { $$ = parser->ast_operation (BINOP_GTR, $1, $3); }
707 { $$ = parser->ast_operation (BINOP_BITWISE_AND, $1, $3); }
710 { $$ = parser->ast_operation (BINOP_BITWISE_IOR, $1, $3); }
713 { $$ = parser->ast_operation (BINOP_BITWISE_XOR, $1, $3); }
716 { $$ = parser->ast_operation (BINOP_ADD, $1, $3); }
719 { $$ = parser->ast_operation (BINOP_SUB, $1, $3); }
722 { $$ = parser->ast_operation (BINOP_LOGICAL_OR, $1, $3); }
725 { $$ = parser->ast_operation (BINOP_LOGICAL_AND, $1, $3); }
728 { $$ = parser->ast_operation (BINOP_EQUAL, $1, $3); }
731 { $$ = parser->ast_operation (BINOP_NOTEQUAL, $1, $3); }
734 { $$ = parser->ast_operation (BINOP_LEQ, $1, $3); }
737 { $$ = parser->ast_operation (BINOP_GEQ, $1, $3); }
740 { $$ = parser->ast_operation (BINOP_LSH, $1, $3); }
743 { $$ = parser->ast_operation (BINOP_RSH, $1, $3); }
748 { $$ = parser->ast_cast ($1, $3); }
753 { $$ = parser->ast_operation (BINOP_ASSIGN, $1, $3); }
756 compound_assignment_expr:
757 expr COMPOUND_ASSIGN expr
758 { $$ = parser->ast_compound_assignment ($2, $1, $3); }
770 $$ = parser->new_op_vector ();
783 /* The result can't be NULL. */
784 $$ = parser->new_op_vector ();
791 '(' maybe_expr_list ')'
797 { $$ = parser->ast_call_ish (OP_FUNCALL, $1, $2); }
808 | super_path KW_SUPER COLONCOLON
816 { $$ = parser->ast_path ($1, NULL); }
818 { $$ = parser->ast_path (make_stoken ("self"), NULL); }
822 identifier_path_for_expr
823 | KW_SELF COLONCOLON identifier_path_for_expr
824 { $$ = parser->super_name ($3, 0); }
825 | maybe_self_path super_path identifier_path_for_expr
826 { $$ = parser->super_name ($3, $2); }
827 | COLONCOLON identifier_path_for_expr
828 { $$ = parser->crate_name ($2); }
829 | KW_EXTERN identifier_path_for_expr
831 /* This is a gdb extension to make it possible to
832 refer to items in other crates. It just bypasses
833 adding the current crate to the front of the
835 $$ = parser->ast_path (parser->concat3 ("::",
842 identifier_path_for_expr:
844 { $$ = parser->ast_path ($1, NULL); }
845 | identifier_path_for_expr COLONCOLON IDENT
847 $$ = parser->ast_path (parser->concat3 ($1->left.sval.ptr,
851 | identifier_path_for_expr COLONCOLON '<' type_list '>'
852 { $$ = parser->ast_path ($1->left.sval, $4); }
853 | identifier_path_for_expr COLONCOLON '<' type_list RSH
855 $$ = parser->ast_path ($1->left.sval, $4);
856 rust_push_back ('>');
861 identifier_path_for_type
862 | KW_SELF COLONCOLON identifier_path_for_type
863 { $$ = parser->super_name ($3, 0); }
864 | maybe_self_path super_path identifier_path_for_type
865 { $$ = parser->super_name ($3, $2); }
866 | COLONCOLON identifier_path_for_type
867 { $$ = parser->crate_name ($2); }
868 | KW_EXTERN identifier_path_for_type
870 /* This is a gdb extension to make it possible to
871 refer to items in other crates. It just bypasses
872 adding the current crate to the front of the
874 $$ = parser->ast_path (parser->concat3 ("::",
881 just_identifiers_for_type:
883 { $$ = parser->ast_path ($1, NULL); }
884 | just_identifiers_for_type COLONCOLON IDENT
886 $$ = parser->ast_path (parser->concat3 ($1->left.sval.ptr,
892 identifier_path_for_type:
893 just_identifiers_for_type
894 | just_identifiers_for_type '<' type_list '>'
895 { $$ = parser->ast_path ($1->left.sval, $3); }
896 | just_identifiers_for_type '<' type_list RSH
898 $$ = parser->ast_path ($1->left.sval, $3);
899 rust_push_back ('>');
905 | '[' type ';' INTEGER ']'
906 { $$ = parser->ast_array_type ($2, $4); }
907 | '[' type ';' DECIMAL_INTEGER ']'
908 { $$ = parser->ast_array_type ($2, $4); }
910 { $$ = parser->ast_slice_type ($3); }
912 { $$ = parser->ast_reference_type ($2); }
914 { $$ = parser->ast_pointer_type ($3, 1); }
916 { $$ = parser->ast_pointer_type ($3, 0); }
917 | KW_FN '(' maybe_type_list ')' ARROW type
918 { $$ = parser->ast_function_type ($6, $3); }
919 | '(' maybe_type_list ')'
920 { $$ = parser->ast_tuple_type ($2); }
933 rust_op_vector *result = parser->new_op_vector ();
934 result->push_back ($1);
946 /* A struct of this type is used to describe a token. */
952 enum exp_opcode opcode;
955 /* Identifier tokens. */
957 static const struct token_info identifier_tokens[] =
959 { "as", KW_AS, OP_NULL },
960 { "false", KW_FALSE, OP_NULL },
961 { "if", 0, OP_NULL },
962 { "mut", KW_MUT, OP_NULL },
963 { "const", KW_CONST, OP_NULL },
964 { "self", KW_SELF, OP_NULL },
965 { "super", KW_SUPER, OP_NULL },
966 { "true", KW_TRUE, OP_NULL },
967 { "extern", KW_EXTERN, OP_NULL },
968 { "fn", KW_FN, OP_NULL },
969 { "sizeof", KW_SIZEOF, OP_NULL },
972 /* Operator tokens, sorted longest first. */
974 static const struct token_info operator_tokens[] =
976 { ">>=", COMPOUND_ASSIGN, BINOP_RSH },
977 { "<<=", COMPOUND_ASSIGN, BINOP_LSH },
979 { "<<", LSH, OP_NULL },
980 { ">>", RSH, OP_NULL },
981 { "&&", ANDAND, OP_NULL },
982 { "||", OROR, OP_NULL },
983 { "==", EQEQ, OP_NULL },
984 { "!=", NOTEQ, OP_NULL },
985 { "<=", LTEQ, OP_NULL },
986 { ">=", GTEQ, OP_NULL },
987 { "+=", COMPOUND_ASSIGN, BINOP_ADD },
988 { "-=", COMPOUND_ASSIGN, BINOP_SUB },
989 { "*=", COMPOUND_ASSIGN, BINOP_MUL },
990 { "/=", COMPOUND_ASSIGN, BINOP_DIV },
991 { "%=", COMPOUND_ASSIGN, BINOP_REM },
992 { "&=", COMPOUND_ASSIGN, BINOP_BITWISE_AND },
993 { "|=", COMPOUND_ASSIGN, BINOP_BITWISE_IOR },
994 { "^=", COMPOUND_ASSIGN, BINOP_BITWISE_XOR },
995 { "..=", DOTDOTEQ, OP_NULL },
997 { "::", COLONCOLON, OP_NULL },
998 { "..", DOTDOT, OP_NULL },
999 { "->", ARROW, OP_NULL }
1002 /* Helper function to copy to the name obstack. */
1005 rust_parser::copy_name (const char *name, int len)
1007 return (const char *) obstack_copy0 (&obstack, name, len);
1010 /* Helper function to make an stoken from a C string. */
1012 static struct stoken
1013 make_stoken (const char *p)
1015 struct stoken result;
1018 result.length = strlen (result.ptr);
1022 /* Helper function to concatenate three strings on the name
1026 rust_parser::concat3 (const char *s1, const char *s2, const char *s3)
1028 return make_stoken (obconcat (&obstack, s1, s2, s3, (char *) NULL));
1031 /* Return an AST node referring to NAME, but relative to the crate's
1034 const struct rust_op *
1035 rust_parser::crate_name (const struct rust_op *name)
1037 std::string crate = rust_crate_for_block (expression_context_block);
1038 struct stoken result;
1040 gdb_assert (name->opcode == OP_VAR_VALUE);
1043 error (_("Could not find crate for current location"));
1044 result = make_stoken (obconcat (&obstack, "::", crate.c_str (), "::",
1045 name->left.sval.ptr, (char *) NULL));
1047 return ast_path (result, name->right.params);
1050 /* Create an AST node referring to a "super::" qualified name. IDENT
1051 is the base name and N_SUPERS is how many "super::"s were
1052 provided. N_SUPERS can be zero. */
1054 const struct rust_op *
1055 rust_parser::super_name (const struct rust_op *ident, unsigned int n_supers)
1057 const char *scope = block_scope (expression_context_block);
1060 gdb_assert (ident->opcode == OP_VAR_VALUE);
1062 if (scope[0] == '\0')
1063 error (_("Couldn't find namespace scope for self::"));
1068 std::vector<int> offsets;
1069 unsigned int current_len;
1071 current_len = cp_find_first_component (scope);
1072 while (scope[current_len] != '\0')
1074 offsets.push_back (current_len);
1075 gdb_assert (scope[current_len] == ':');
1078 current_len += cp_find_first_component (scope
1082 len = offsets.size ();
1083 if (n_supers >= len)
1084 error (_("Too many super:: uses from '%s'"), scope);
1086 offset = offsets[len - n_supers];
1089 offset = strlen (scope);
1091 obstack_grow (&obstack, "::", 2);
1092 obstack_grow (&obstack, scope, offset);
1093 obstack_grow (&obstack, "::", 2);
1094 obstack_grow0 (&obstack, ident->left.sval.ptr, ident->left.sval.length);
1096 return ast_path (make_stoken ((const char *) obstack_finish (&obstack)),
1097 ident->right.params);
1100 /* A helper that updates the innermost block as appropriate. */
1103 update_innermost_block (struct block_symbol sym)
1105 if (symbol_read_needs_frame (sym.symbol))
1106 innermost_block.update (sym);
1109 /* Lex a hex number with at least MIN digits and at most MAX
1113 lex_hex (int min, int max)
1115 uint32_t result = 0;
1117 /* We only want to stop at MAX if we're lexing a byte escape. */
1118 int check_max = min == max;
1120 while ((check_max ? len <= max : 1)
1121 && ((lexptr[0] >= 'a' && lexptr[0] <= 'f')
1122 || (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1123 || (lexptr[0] >= '0' && lexptr[0] <= '9')))
1126 if (lexptr[0] >= 'a' && lexptr[0] <= 'f')
1127 result = result + 10 + lexptr[0] - 'a';
1128 else if (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1129 result = result + 10 + lexptr[0] - 'A';
1131 result = result + lexptr[0] - '0';
1137 error (_("Not enough hex digits seen"));
1140 gdb_assert (min != max);
1141 error (_("Overlong hex escape"));
1147 /* Lex an escape. IS_BYTE is true if we're lexing a byte escape;
1148 otherwise we're lexing a character escape. */
1151 lex_escape (int is_byte)
1155 gdb_assert (lexptr[0] == '\\');
1161 result = lex_hex (2, 2);
1166 error (_("Unicode escape in byte literal"));
1168 if (lexptr[0] != '{')
1169 error (_("Missing '{' in Unicode escape"));
1171 result = lex_hex (1, 6);
1172 /* Could do range checks here. */
1173 if (lexptr[0] != '}')
1174 error (_("Missing '}' in Unicode escape"));
1208 error (_("Invalid escape \\%c in literal"), lexptr[0]);
1214 /* Lex a character constant. */
1217 rust_parser::lex_character (YYSTYPE *lvalp)
1222 if (lexptr[0] == 'b')
1227 gdb_assert (lexptr[0] == '\'');
1229 /* This should handle UTF-8 here. */
1230 if (lexptr[0] == '\\')
1231 value = lex_escape (is_byte);
1234 value = lexptr[0] & 0xff;
1238 if (lexptr[0] != '\'')
1239 error (_("Unterminated character literal"));
1242 lvalp->typed_val_int.val = value;
1243 lvalp->typed_val_int.type = get_type (is_byte ? "u8" : "char");
1248 /* Return the offset of the double quote if STR looks like the start
1249 of a raw string, or 0 if STR does not start a raw string. */
1252 starts_raw_string (const char *str)
1254 const char *save = str;
1259 while (str[0] == '#')
1266 /* Return true if STR looks like the end of a raw string that had N
1267 hashes at the start. */
1270 ends_raw_string (const char *str, int n)
1274 gdb_assert (str[0] == '"');
1275 for (i = 0; i < n; ++i)
1276 if (str[i + 1] != '#')
1281 /* Lex a string constant. */
1284 rust_parser::lex_string (YYSTYPE *lvalp)
1286 int is_byte = lexptr[0] == 'b';
1291 raw_length = starts_raw_string (lexptr);
1292 lexptr += raw_length;
1293 gdb_assert (lexptr[0] == '"');
1302 if (lexptr[0] == '"' && ends_raw_string (lexptr, raw_length - 1))
1304 /* Exit with lexptr pointing after the final "#". */
1305 lexptr += raw_length;
1308 else if (lexptr[0] == '\0')
1309 error (_("Unexpected EOF in string"));
1311 value = lexptr[0] & 0xff;
1312 if (is_byte && value > 127)
1313 error (_("Non-ASCII value in raw byte string"));
1314 obstack_1grow (&obstack, value);
1318 else if (lexptr[0] == '"')
1320 /* Make sure to skip the quote. */
1324 else if (lexptr[0] == '\\')
1326 value = lex_escape (is_byte);
1329 obstack_1grow (&obstack, value);
1331 convert_between_encodings ("UTF-32", "UTF-8", (gdb_byte *) &value,
1332 sizeof (value), sizeof (value),
1333 &obstack, translit_none);
1335 else if (lexptr[0] == '\0')
1336 error (_("Unexpected EOF in string"));
1339 value = lexptr[0] & 0xff;
1340 if (is_byte && value > 127)
1341 error (_("Non-ASCII value in byte string"));
1342 obstack_1grow (&obstack, value);
1347 lvalp->sval.length = obstack_object_size (&obstack);
1348 lvalp->sval.ptr = (const char *) obstack_finish (&obstack);
1349 return is_byte ? BYTESTRING : STRING;
1352 /* Return true if STRING starts with whitespace followed by a digit. */
1355 space_then_number (const char *string)
1357 const char *p = string;
1359 while (p[0] == ' ' || p[0] == '\t')
1364 return *p >= '0' && *p <= '9';
1367 /* Return true if C can start an identifier. */
1370 rust_identifier_start_p (char c)
1372 return ((c >= 'a' && c <= 'z')
1373 || (c >= 'A' && c <= 'Z')
1378 /* Lex an identifier. */
1381 rust_parser::lex_identifier (YYSTYPE *lvalp)
1383 const char *start = lexptr;
1384 unsigned int length;
1385 const struct token_info *token;
1387 int is_gdb_var = lexptr[0] == '$';
1389 gdb_assert (rust_identifier_start_p (lexptr[0]));
1393 /* For the time being this doesn't handle Unicode rules. Non-ASCII
1394 identifiers are gated anyway. */
1395 while ((lexptr[0] >= 'a' && lexptr[0] <= 'z')
1396 || (lexptr[0] >= 'A' && lexptr[0] <= 'Z')
1398 || (is_gdb_var && lexptr[0] == '$')
1399 || (lexptr[0] >= '0' && lexptr[0] <= '9'))
1403 length = lexptr - start;
1405 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
1407 if (length == strlen (identifier_tokens[i].name)
1408 && strncmp (identifier_tokens[i].name, start, length) == 0)
1410 token = &identifier_tokens[i];
1417 if (token->value == 0)
1419 /* Leave the terminating token alone. */
1424 else if (token == NULL
1425 && (strncmp (start, "thread", length) == 0
1426 || strncmp (start, "task", length) == 0)
1427 && space_then_number (lexptr))
1429 /* "task" or "thread" followed by a number terminates the
1430 parse, per gdb rules. */
1435 if (token == NULL || (parse_completion && lexptr[0] == '\0'))
1436 lvalp->sval = make_stoken (copy_name (start, length));
1438 if (parse_completion && lexptr[0] == '\0')
1440 /* Prevent rustyylex from returning two COMPLETE tokens. */
1441 prev_lexptr = lexptr;
1446 return token->value;
1452 /* Lex an operator. */
1455 lex_operator (YYSTYPE *lvalp)
1457 const struct token_info *token = NULL;
1460 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
1462 if (strncmp (operator_tokens[i].name, lexptr,
1463 strlen (operator_tokens[i].name)) == 0)
1465 lexptr += strlen (operator_tokens[i].name);
1466 token = &operator_tokens[i];
1473 lvalp->opcode = token->opcode;
1474 return token->value;
1483 rust_parser::lex_number (YYSTYPE *lvalp)
1485 regmatch_t subexps[NUM_SUBEXPRESSIONS];
1488 int could_be_decimal = 1;
1489 int implicit_i32 = 0;
1490 const char *type_name = NULL;
1493 int type_index = -1;
1496 match = regexec (&number_regex, lexptr, ARRAY_SIZE (subexps), subexps, 0);
1497 /* Failure means the regexp is broken. */
1498 gdb_assert (match == 0);
1500 if (subexps[INT_TEXT].rm_so != -1)
1502 /* Integer part matched. */
1504 end_index = subexps[INT_TEXT].rm_eo;
1505 if (subexps[INT_TYPE].rm_so == -1)
1512 type_index = INT_TYPE;
1513 could_be_decimal = 0;
1516 else if (subexps[FLOAT_TYPE1].rm_so != -1)
1518 /* Found floating point type suffix. */
1519 end_index = subexps[FLOAT_TYPE1].rm_so;
1520 type_index = FLOAT_TYPE1;
1522 else if (subexps[FLOAT_TYPE2].rm_so != -1)
1524 /* Found floating point type suffix. */
1525 end_index = subexps[FLOAT_TYPE2].rm_so;
1526 type_index = FLOAT_TYPE2;
1530 /* Any other floating point match. */
1531 end_index = subexps[0].rm_eo;
1535 /* We need a special case if the final character is ".". In this
1536 case we might need to parse an integer. For example, "23.f()" is
1537 a request for a trait method call, not a syntax error involving
1538 the floating point number "23.". */
1539 gdb_assert (subexps[0].rm_eo > 0);
1540 if (lexptr[subexps[0].rm_eo - 1] == '.')
1542 const char *next = skip_spaces (&lexptr[subexps[0].rm_eo]);
1544 if (rust_identifier_start_p (*next) || *next == '.')
1548 end_index = subexps[0].rm_eo;
1550 could_be_decimal = 1;
1555 /* Compute the type name if we haven't already. */
1556 std::string type_name_holder;
1557 if (type_name == NULL)
1559 gdb_assert (type_index != -1);
1560 type_name_holder = std::string (lexptr + subexps[type_index].rm_so,
1561 (subexps[type_index].rm_eo
1562 - subexps[type_index].rm_so));
1563 type_name = type_name_holder.c_str ();
1566 /* Look up the type. */
1567 type = get_type (type_name);
1569 /* Copy the text of the number and remove the "_"s. */
1571 for (i = 0; i < end_index && lexptr[i]; ++i)
1573 if (lexptr[i] == '_')
1574 could_be_decimal = 0;
1576 number.push_back (lexptr[i]);
1579 /* Advance past the match. */
1580 lexptr += subexps[0].rm_eo;
1582 /* Parse the number. */
1589 if (number[0] == '0')
1591 if (number[1] == 'x')
1593 else if (number[1] == 'o')
1595 else if (number[1] == 'b')
1600 could_be_decimal = 0;
1604 value = strtoul (number.c_str () + offset, NULL, radix);
1605 if (implicit_i32 && value >= ((uint64_t) 1) << 31)
1606 type = get_type ("i64");
1608 lvalp->typed_val_int.val = value;
1609 lvalp->typed_val_int.type = type;
1613 lvalp->typed_val_float.type = type;
1614 bool parsed = parse_float (number.c_str (), number.length (),
1615 lvalp->typed_val_float.type,
1616 lvalp->typed_val_float.val);
1617 gdb_assert (parsed);
1620 return is_integer ? (could_be_decimal ? DECIMAL_INTEGER : INTEGER) : FLOAT;
1626 rustyylex (YYSTYPE *lvalp, rust_parser *parser)
1628 /* Skip all leading whitespace. */
1629 while (lexptr[0] == ' ' || lexptr[0] == '\t' || lexptr[0] == '\r'
1630 || lexptr[0] == '\n')
1633 /* If we hit EOF and we're completing, then return COMPLETE -- maybe
1634 we're completing an empty string at the end of a field_expr.
1635 But, we don't want to return two COMPLETE tokens in a row. */
1636 if (lexptr[0] == '\0' && lexptr == prev_lexptr)
1638 prev_lexptr = lexptr;
1639 if (lexptr[0] == '\0')
1641 if (parse_completion)
1643 lvalp->sval = make_stoken ("");
1649 if (lexptr[0] >= '0' && lexptr[0] <= '9')
1650 return parser->lex_number (lvalp);
1651 else if (lexptr[0] == 'b' && lexptr[1] == '\'')
1652 return parser->lex_character (lvalp);
1653 else if (lexptr[0] == 'b' && lexptr[1] == '"')
1654 return parser->lex_string (lvalp);
1655 else if (lexptr[0] == 'b' && starts_raw_string (lexptr + 1))
1656 return parser->lex_string (lvalp);
1657 else if (starts_raw_string (lexptr))
1658 return parser->lex_string (lvalp);
1659 else if (rust_identifier_start_p (lexptr[0]))
1660 return parser->lex_identifier (lvalp);
1661 else if (lexptr[0] == '"')
1662 return parser->lex_string (lvalp);
1663 else if (lexptr[0] == '\'')
1664 return parser->lex_character (lvalp);
1665 else if (lexptr[0] == '}' || lexptr[0] == ']')
1667 /* Falls through to lex_operator. */
1670 else if (lexptr[0] == '(' || lexptr[0] == '{')
1672 /* Falls through to lex_operator. */
1675 else if (lexptr[0] == ',' && comma_terminates && paren_depth == 0)
1678 return lex_operator (lvalp);
1681 /* Push back a single character to be re-lexed. */
1684 rust_push_back (char c)
1686 /* Can't be called before any lexing. */
1687 gdb_assert (prev_lexptr != NULL);
1690 gdb_assert (*lexptr == c);
1695 /* Make an arbitrary operation and fill in the fields. */
1697 const struct rust_op *
1698 rust_parser::ast_operation (enum exp_opcode opcode, const struct rust_op *left,
1699 const struct rust_op *right)
1701 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1703 result->opcode = opcode;
1704 result->left.op = left;
1705 result->right.op = right;
1710 /* Make a compound assignment operation. */
1712 const struct rust_op *
1713 rust_parser::ast_compound_assignment (enum exp_opcode opcode,
1714 const struct rust_op *left,
1715 const struct rust_op *right)
1717 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1719 result->opcode = opcode;
1720 result->compound_assignment = 1;
1721 result->left.op = left;
1722 result->right.op = right;
1727 /* Make a typed integer literal operation. */
1729 const struct rust_op *
1730 rust_parser::ast_literal (struct typed_val_int val)
1732 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1734 result->opcode = OP_LONG;
1735 result->left.typed_val_int = val;
1740 /* Make a typed floating point literal operation. */
1742 const struct rust_op *
1743 rust_parser::ast_dliteral (struct typed_val_float val)
1745 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1747 result->opcode = OP_FLOAT;
1748 result->left.typed_val_float = val;
1753 /* Make a unary operation. */
1755 const struct rust_op *
1756 rust_parser::ast_unary (enum exp_opcode opcode, const struct rust_op *expr)
1758 return ast_operation (opcode, expr, NULL);
1761 /* Make a cast operation. */
1763 const struct rust_op *
1764 rust_parser::ast_cast (const struct rust_op *expr, const struct rust_op *type)
1766 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1768 result->opcode = UNOP_CAST;
1769 result->left.op = expr;
1770 result->right.op = type;
1775 /* Make a call-like operation. This is nominally a function call, but
1776 when lowering we may discover that it actually represents the
1777 creation of a tuple struct. */
1779 const struct rust_op *
1780 rust_parser::ast_call_ish (enum exp_opcode opcode, const struct rust_op *expr,
1781 rust_op_vector *params)
1783 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1785 result->opcode = opcode;
1786 result->left.op = expr;
1787 result->right.params = params;
1792 /* Make a structure creation operation. */
1794 const struct rust_op *
1795 rust_parser::ast_struct (const struct rust_op *name, rust_set_vector *fields)
1797 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1799 result->opcode = OP_AGGREGATE;
1800 result->left.op = name;
1801 result->right.field_inits = fields;
1806 /* Make an identifier path. */
1808 const struct rust_op *
1809 rust_parser::ast_path (struct stoken path, rust_op_vector *params)
1811 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1813 result->opcode = OP_VAR_VALUE;
1814 result->left.sval = path;
1815 result->right.params = params;
1820 /* Make a string constant operation. */
1822 const struct rust_op *
1823 rust_parser::ast_string (struct stoken str)
1825 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1827 result->opcode = OP_STRING;
1828 result->left.sval = str;
1833 /* Make a field expression. */
1835 const struct rust_op *
1836 rust_parser::ast_structop (const struct rust_op *left, const char *name,
1839 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1841 result->opcode = STRUCTOP_STRUCT;
1842 result->completing = completing;
1843 result->left.op = left;
1844 result->right.sval = make_stoken (name);
1849 /* Make an anonymous struct operation, like 'x.0'. */
1851 const struct rust_op *
1852 rust_parser::ast_structop_anonymous (const struct rust_op *left,
1853 struct typed_val_int number)
1855 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1857 result->opcode = STRUCTOP_ANONYMOUS;
1858 result->left.op = left;
1859 result->right.typed_val_int = number;
1864 /* Make a range operation. */
1866 const struct rust_op *
1867 rust_parser::ast_range (const struct rust_op *lhs, const struct rust_op *rhs,
1870 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1872 result->opcode = OP_RANGE;
1873 result->inclusive = inclusive;
1874 result->left.op = lhs;
1875 result->right.op = rhs;
1880 /* A helper function to make a type-related AST node. */
1883 rust_parser::ast_basic_type (enum type_code typecode)
1885 struct rust_op *result = OBSTACK_ZALLOC (&obstack, struct rust_op);
1887 result->opcode = OP_TYPE;
1888 result->typecode = typecode;
1892 /* Create an AST node describing an array type. */
1894 const struct rust_op *
1895 rust_parser::ast_array_type (const struct rust_op *lhs,
1896 struct typed_val_int val)
1898 struct rust_op *result = ast_basic_type (TYPE_CODE_ARRAY);
1900 result->left.op = lhs;
1901 result->right.typed_val_int = val;
1905 /* Create an AST node describing a reference type. */
1907 const struct rust_op *
1908 rust_parser::ast_slice_type (const struct rust_op *type)
1910 /* Use TYPE_CODE_COMPLEX just because it is handy. */
1911 struct rust_op *result = ast_basic_type (TYPE_CODE_COMPLEX);
1913 result->left.op = type;
1917 /* Create an AST node describing a reference type. */
1919 const struct rust_op *
1920 rust_parser::ast_reference_type (const struct rust_op *type)
1922 struct rust_op *result = ast_basic_type (TYPE_CODE_REF);
1924 result->left.op = type;
1928 /* Create an AST node describing a pointer type. */
1930 const struct rust_op *
1931 rust_parser::ast_pointer_type (const struct rust_op *type, int is_mut)
1933 struct rust_op *result = ast_basic_type (TYPE_CODE_PTR);
1935 result->left.op = type;
1936 /* For the time being we ignore is_mut. */
1940 /* Create an AST node describing a function type. */
1942 const struct rust_op *
1943 rust_parser::ast_function_type (const struct rust_op *rtype,
1944 rust_op_vector *params)
1946 struct rust_op *result = ast_basic_type (TYPE_CODE_FUNC);
1948 result->left.op = rtype;
1949 result->right.params = params;
1953 /* Create an AST node describing a tuple type. */
1955 const struct rust_op *
1956 rust_parser::ast_tuple_type (rust_op_vector *params)
1958 struct rust_op *result = ast_basic_type (TYPE_CODE_STRUCT);
1960 result->left.params = params;
1964 /* A helper to appropriately munge NAME and BLOCK depending on the
1965 presence of a leading "::". */
1968 munge_name_and_block (const char **name, const struct block **block)
1970 /* If it is a global reference, skip the current block in favor of
1971 the static block. */
1972 if (strncmp (*name, "::", 2) == 0)
1975 *block = block_static_block (*block);
1979 /* Like lookup_symbol, but handles Rust namespace conventions, and
1980 doesn't require field_of_this_result. */
1982 static struct block_symbol
1983 rust_lookup_symbol (const char *name, const struct block *block,
1984 const domain_enum domain)
1986 struct block_symbol result;
1988 munge_name_and_block (&name, &block);
1990 result = lookup_symbol (name, block, domain, NULL);
1991 if (result.symbol != NULL)
1992 update_innermost_block (result);
1996 /* Look up a type, following Rust namespace conventions. */
1999 rust_parser::rust_lookup_type (const char *name, const struct block *block)
2001 struct block_symbol result;
2004 munge_name_and_block (&name, &block);
2006 result = lookup_symbol (name, block, STRUCT_DOMAIN, NULL);
2007 if (result.symbol != NULL)
2009 update_innermost_block (result);
2010 return SYMBOL_TYPE (result.symbol);
2013 type = lookup_typename (language (), arch (), name, NULL, 1);
2017 /* Last chance, try a built-in type. */
2018 return language_lookup_primitive_type (language (), arch (), name);
2021 /* Convert a vector of rust_ops representing types to a vector of
2024 std::vector<struct type *>
2025 rust_parser::convert_params_to_types (rust_op_vector *params)
2027 std::vector<struct type *> result;
2029 if (params != nullptr)
2031 for (const rust_op *op : *params)
2032 result.push_back (convert_ast_to_type (op));
2038 /* Convert a rust_op representing a type to a struct type *. */
2041 rust_parser::convert_ast_to_type (const struct rust_op *operation)
2043 struct type *type, *result = NULL;
2045 if (operation->opcode == OP_VAR_VALUE)
2047 const char *varname = convert_name (operation);
2049 result = rust_lookup_type (varname, expression_context_block);
2051 error (_("No typed name '%s' in current context"), varname);
2055 gdb_assert (operation->opcode == OP_TYPE);
2057 switch (operation->typecode)
2059 case TYPE_CODE_ARRAY:
2060 type = convert_ast_to_type (operation->left.op);
2061 if (operation->right.typed_val_int.val < 0)
2062 error (_("Negative array length"));
2063 result = lookup_array_range_type (type, 0,
2064 operation->right.typed_val_int.val - 1);
2067 case TYPE_CODE_COMPLEX:
2069 struct type *usize = get_type ("usize");
2071 type = convert_ast_to_type (operation->left.op);
2072 result = rust_slice_type ("&[*gdb*]", type, usize);
2078 /* For now we treat &x and *x identically. */
2079 type = convert_ast_to_type (operation->left.op);
2080 result = lookup_pointer_type (type);
2083 case TYPE_CODE_FUNC:
2085 std::vector<struct type *> args
2086 (convert_params_to_types (operation->right.params));
2087 struct type **argtypes = NULL;
2089 type = convert_ast_to_type (operation->left.op);
2091 argtypes = args.data ();
2094 = lookup_function_type_with_arguments (type, args.size (),
2096 result = lookup_pointer_type (result);
2100 case TYPE_CODE_STRUCT:
2102 std::vector<struct type *> args
2103 (convert_params_to_types (operation->left.params));
2107 obstack_1grow (&obstack, '(');
2108 for (i = 0; i < args.size (); ++i)
2110 std::string type_name = type_to_string (args[i]);
2113 obstack_1grow (&obstack, ',');
2114 obstack_grow_str (&obstack, type_name.c_str ());
2117 obstack_grow_str0 (&obstack, ")");
2118 name = (const char *) obstack_finish (&obstack);
2120 /* We don't allow creating new tuple types (yet), but we do
2121 allow looking up existing tuple types. */
2122 result = rust_lookup_type (name, expression_context_block);
2124 error (_("could not find tuple type '%s'"), name);
2129 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_type");
2132 gdb_assert (result != NULL);
2136 /* A helper function to turn a rust_op representing a name into a full
2137 name. This applies generic arguments as needed. The returned name
2138 is allocated on the work obstack. */
2141 rust_parser::convert_name (const struct rust_op *operation)
2145 gdb_assert (operation->opcode == OP_VAR_VALUE);
2147 if (operation->right.params == NULL)
2148 return operation->left.sval.ptr;
2150 std::vector<struct type *> types
2151 (convert_params_to_types (operation->right.params));
2153 obstack_grow_str (&obstack, operation->left.sval.ptr);
2154 obstack_1grow (&obstack, '<');
2155 for (i = 0; i < types.size (); ++i)
2157 std::string type_name = type_to_string (types[i]);
2160 obstack_1grow (&obstack, ',');
2162 obstack_grow_str (&obstack, type_name.c_str ());
2164 obstack_grow_str0 (&obstack, ">");
2166 return (const char *) obstack_finish (&obstack);
2169 /* A helper function that converts a vec of rust_ops to a gdb
2173 rust_parser::convert_params_to_expression (rust_op_vector *params,
2174 const struct rust_op *top)
2176 for (const rust_op *elem : *params)
2177 convert_ast_to_expression (elem, top);
2180 /* Lower a rust_op to a gdb expression. STATE is the parser state.
2181 OPERATION is the operation to lower. TOP is a pointer to the
2182 top-most operation; it is used to handle the special case where the
2183 top-most expression is an identifier and can be optionally lowered
2184 to OP_TYPE. WANT_TYPE is a flag indicating that, if the expression
2185 is the name of a type, then emit an OP_TYPE for it (rather than
2186 erroring). If WANT_TYPE is set, then the similar TOP handling is
2190 rust_parser::convert_ast_to_expression (const struct rust_op *operation,
2191 const struct rust_op *top,
2194 switch (operation->opcode)
2197 write_exp_elt_opcode (pstate, OP_LONG);
2198 write_exp_elt_type (pstate, operation->left.typed_val_int.type);
2199 write_exp_elt_longcst (pstate, operation->left.typed_val_int.val);
2200 write_exp_elt_opcode (pstate, OP_LONG);
2204 write_exp_elt_opcode (pstate, OP_FLOAT);
2205 write_exp_elt_type (pstate, operation->left.typed_val_float.type);
2206 write_exp_elt_floatcst (pstate, operation->left.typed_val_float.val);
2207 write_exp_elt_opcode (pstate, OP_FLOAT);
2210 case STRUCTOP_STRUCT:
2212 convert_ast_to_expression (operation->left.op, top);
2214 if (operation->completing)
2215 mark_struct_expression (pstate);
2216 write_exp_elt_opcode (pstate, STRUCTOP_STRUCT);
2217 write_exp_string (pstate, operation->right.sval);
2218 write_exp_elt_opcode (pstate, STRUCTOP_STRUCT);
2222 case STRUCTOP_ANONYMOUS:
2224 convert_ast_to_expression (operation->left.op, top);
2226 write_exp_elt_opcode (pstate, STRUCTOP_ANONYMOUS);
2227 write_exp_elt_longcst (pstate, operation->right.typed_val_int.val);
2228 write_exp_elt_opcode (pstate, STRUCTOP_ANONYMOUS);
2233 convert_ast_to_expression (operation->left.op, top, true);
2234 write_exp_elt_opcode (pstate, UNOP_SIZEOF);
2239 case UNOP_COMPLEMENT:
2242 convert_ast_to_expression (operation->left.op, top);
2243 write_exp_elt_opcode (pstate, operation->opcode);
2246 case BINOP_SUBSCRIPT:
2253 case BINOP_BITWISE_AND:
2254 case BINOP_BITWISE_IOR:
2255 case BINOP_BITWISE_XOR:
2258 case BINOP_LOGICAL_OR:
2259 case BINOP_LOGICAL_AND:
2261 case BINOP_NOTEQUAL:
2268 convert_ast_to_expression (operation->left.op, top);
2269 convert_ast_to_expression (operation->right.op, top);
2270 if (operation->compound_assignment)
2272 write_exp_elt_opcode (pstate, BINOP_ASSIGN_MODIFY);
2273 write_exp_elt_opcode (pstate, operation->opcode);
2274 write_exp_elt_opcode (pstate, BINOP_ASSIGN_MODIFY);
2277 write_exp_elt_opcode (pstate, operation->opcode);
2279 if (operation->compound_assignment
2280 || operation->opcode == BINOP_ASSIGN)
2284 type = language_lookup_primitive_type (parse_language (pstate),
2285 parse_gdbarch (pstate),
2288 write_exp_elt_opcode (pstate, OP_LONG);
2289 write_exp_elt_type (pstate, type);
2290 write_exp_elt_longcst (pstate, 0);
2291 write_exp_elt_opcode (pstate, OP_LONG);
2293 write_exp_elt_opcode (pstate, BINOP_COMMA);
2299 struct type *type = convert_ast_to_type (operation->right.op);
2301 convert_ast_to_expression (operation->left.op, top);
2302 write_exp_elt_opcode (pstate, UNOP_CAST);
2303 write_exp_elt_type (pstate, type);
2304 write_exp_elt_opcode (pstate, UNOP_CAST);
2310 if (operation->left.op->opcode == OP_VAR_VALUE)
2313 const char *varname = convert_name (operation->left.op);
2315 type = rust_lookup_type (varname, expression_context_block);
2318 /* This is actually a tuple struct expression, not a
2320 rust_op_vector *params = operation->right.params;
2322 if (TYPE_CODE (type) != TYPE_CODE_NAMESPACE)
2324 if (!rust_tuple_struct_type_p (type))
2325 error (_("Type %s is not a tuple struct"), varname);
2327 for (int i = 0; i < params->size (); ++i)
2329 char *cell = get_print_cell ();
2331 xsnprintf (cell, PRINT_CELL_SIZE, "__%d", i);
2332 write_exp_elt_opcode (pstate, OP_NAME);
2333 write_exp_string (pstate, make_stoken (cell));
2334 write_exp_elt_opcode (pstate, OP_NAME);
2336 convert_ast_to_expression ((*params)[i], top);
2339 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2340 write_exp_elt_type (pstate, type);
2341 write_exp_elt_longcst (pstate, 2 * params->size ());
2342 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2347 convert_ast_to_expression (operation->left.op, top);
2348 convert_params_to_expression (operation->right.params, top);
2349 write_exp_elt_opcode (pstate, OP_FUNCALL);
2350 write_exp_elt_longcst (pstate, operation->right.params->size ());
2351 write_exp_elt_longcst (pstate, OP_FUNCALL);
2356 gdb_assert (operation->left.op == NULL);
2357 convert_params_to_expression (operation->right.params, top);
2358 write_exp_elt_opcode (pstate, OP_ARRAY);
2359 write_exp_elt_longcst (pstate, 0);
2360 write_exp_elt_longcst (pstate, operation->right.params->size () - 1);
2361 write_exp_elt_longcst (pstate, OP_ARRAY);
2366 struct block_symbol sym;
2367 const char *varname;
2369 if (operation->left.sval.ptr[0] == '$')
2371 write_dollar_variable (pstate, operation->left.sval);
2375 varname = convert_name (operation);
2376 sym = rust_lookup_symbol (varname, expression_context_block,
2378 if (sym.symbol != NULL && SYMBOL_CLASS (sym.symbol) != LOC_TYPEDEF)
2380 write_exp_elt_opcode (pstate, OP_VAR_VALUE);
2381 write_exp_elt_block (pstate, sym.block);
2382 write_exp_elt_sym (pstate, sym.symbol);
2383 write_exp_elt_opcode (pstate, OP_VAR_VALUE);
2387 struct type *type = NULL;
2389 if (sym.symbol != NULL)
2391 gdb_assert (SYMBOL_CLASS (sym.symbol) == LOC_TYPEDEF);
2392 type = SYMBOL_TYPE (sym.symbol);
2395 type = rust_lookup_type (varname, expression_context_block);
2397 error (_("No symbol '%s' in current context"), varname);
2400 && TYPE_CODE (type) == TYPE_CODE_STRUCT
2401 && TYPE_NFIELDS (type) == 0)
2403 /* A unit-like struct. */
2404 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2405 write_exp_elt_type (pstate, type);
2406 write_exp_elt_longcst (pstate, 0);
2407 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2409 else if (want_type || operation == top)
2411 write_exp_elt_opcode (pstate, OP_TYPE);
2412 write_exp_elt_type (pstate, type);
2413 write_exp_elt_opcode (pstate, OP_TYPE);
2416 error (_("Found type '%s', which can't be "
2417 "evaluated in this context"),
2426 rust_set_vector *fields = operation->right.field_inits;
2431 for (const set_field &init : *fields)
2433 if (init.name.ptr != NULL)
2435 write_exp_elt_opcode (pstate, OP_NAME);
2436 write_exp_string (pstate, init.name);
2437 write_exp_elt_opcode (pstate, OP_NAME);
2441 convert_ast_to_expression (init.init, top);
2444 if (init.name.ptr == NULL)
2446 /* This is handled differently from Ada in our
2448 write_exp_elt_opcode (pstate, OP_OTHERS);
2452 name = convert_name (operation->left.op);
2453 type = rust_lookup_type (name, expression_context_block);
2455 error (_("Could not find type '%s'"), operation->left.sval.ptr);
2457 if (TYPE_CODE (type) != TYPE_CODE_STRUCT
2458 || rust_tuple_type_p (type)
2459 || rust_tuple_struct_type_p (type))
2460 error (_("Struct expression applied to non-struct type"));
2462 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2463 write_exp_elt_type (pstate, type);
2464 write_exp_elt_longcst (pstate, length);
2465 write_exp_elt_opcode (pstate, OP_AGGREGATE);
2471 write_exp_elt_opcode (pstate, OP_STRING);
2472 write_exp_string (pstate, operation->left.sval);
2473 write_exp_elt_opcode (pstate, OP_STRING);
2479 enum range_type kind = BOTH_BOUND_DEFAULT;
2481 if (operation->left.op != NULL)
2483 convert_ast_to_expression (operation->left.op, top);
2484 kind = HIGH_BOUND_DEFAULT;
2486 if (operation->right.op != NULL)
2488 convert_ast_to_expression (operation->right.op, top);
2489 if (kind == BOTH_BOUND_DEFAULT)
2490 kind = (operation->inclusive
2491 ? LOW_BOUND_DEFAULT : LOW_BOUND_DEFAULT_EXCLUSIVE);
2494 gdb_assert (kind == HIGH_BOUND_DEFAULT);
2495 kind = (operation->inclusive
2496 ? NONE_BOUND_DEFAULT : NONE_BOUND_DEFAULT_EXCLUSIVE);
2501 /* Nothing should make an inclusive range without an upper
2503 gdb_assert (!operation->inclusive);
2506 write_exp_elt_opcode (pstate, OP_RANGE);
2507 write_exp_elt_longcst (pstate, kind);
2508 write_exp_elt_opcode (pstate, OP_RANGE);
2513 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_expression");
2519 /* The parser as exposed to gdb. */
2522 rust_parse (struct parser_state *state)
2526 /* This sets various globals and also clears them on
2528 rust_parser parser (state);
2530 result = rustyyparse (&parser);
2532 if (!result || (parse_completion && parser.rust_ast != NULL))
2533 parser.convert_ast_to_expression (parser.rust_ast, parser.rust_ast);
2538 /* The parser error handler. */
2541 rustyyerror (rust_parser *parser, const char *msg)
2543 const char *where = prev_lexptr ? prev_lexptr : lexptr;
2544 error (_("%s in expression, near `%s'."), msg, where);
2551 /* Initialize the lexer for testing. */
2554 rust_lex_test_init (const char *input)
2561 /* A test helper that lexes a string, expecting a single token. It
2562 returns the lexer data for this token. */
2565 rust_lex_test_one (rust_parser *parser, const char *input, int expected)
2570 rust_lex_test_init (input);
2572 token = rustyylex (&result, parser);
2573 SELF_CHECK (token == expected);
2578 token = rustyylex (&ignore, parser);
2579 SELF_CHECK (token == 0);
2585 /* Test that INPUT lexes as the integer VALUE. */
2588 rust_lex_int_test (rust_parser *parser, const char *input, int value, int kind)
2590 RUSTSTYPE result = rust_lex_test_one (parser, input, kind);
2591 SELF_CHECK (result.typed_val_int.val == value);
2594 /* Test that INPUT throws an exception with text ERR. */
2597 rust_lex_exception_test (rust_parser *parser, const char *input,
2602 /* The "kind" doesn't matter. */
2603 rust_lex_test_one (parser, input, DECIMAL_INTEGER);
2606 CATCH (except, RETURN_MASK_ERROR)
2608 SELF_CHECK (strcmp (except.message, err) == 0);
2613 /* Test that INPUT lexes as the identifier, string, or byte-string
2614 VALUE. KIND holds the expected token kind. */
2617 rust_lex_stringish_test (rust_parser *parser, const char *input,
2618 const char *value, int kind)
2620 RUSTSTYPE result = rust_lex_test_one (parser, input, kind);
2621 SELF_CHECK (result.sval.length == strlen (value));
2622 SELF_CHECK (strncmp (result.sval.ptr, value, result.sval.length) == 0);
2625 /* Helper to test that a string parses as a given token sequence. */
2628 rust_lex_test_sequence (rust_parser *parser, const char *input, int len,
2629 const int expected[])
2636 for (i = 0; i < len; ++i)
2639 int token = rustyylex (&ignore, parser);
2641 SELF_CHECK (token == expected[i]);
2645 /* Tests for an integer-parsing corner case. */
2648 rust_lex_test_trailing_dot (rust_parser *parser)
2650 const int expected1[] = { DECIMAL_INTEGER, '.', IDENT, '(', ')', 0 };
2651 const int expected2[] = { INTEGER, '.', IDENT, '(', ')', 0 };
2652 const int expected3[] = { FLOAT, EQEQ, '(', ')', 0 };
2653 const int expected4[] = { DECIMAL_INTEGER, DOTDOT, DECIMAL_INTEGER, 0 };
2655 rust_lex_test_sequence (parser, "23.g()", ARRAY_SIZE (expected1), expected1);
2656 rust_lex_test_sequence (parser, "23_0.g()", ARRAY_SIZE (expected2),
2658 rust_lex_test_sequence (parser, "23.==()", ARRAY_SIZE (expected3),
2660 rust_lex_test_sequence (parser, "23..25", ARRAY_SIZE (expected4), expected4);
2663 /* Tests of completion. */
2666 rust_lex_test_completion (rust_parser *parser)
2668 const int expected[] = { IDENT, '.', COMPLETE, 0 };
2670 parse_completion = 1;
2672 rust_lex_test_sequence (parser, "something.wha", ARRAY_SIZE (expected),
2674 rust_lex_test_sequence (parser, "something.", ARRAY_SIZE (expected),
2677 parse_completion = 0;
2680 /* Test pushback. */
2683 rust_lex_test_push_back (rust_parser *parser)
2688 rust_lex_test_init (">>=");
2690 token = rustyylex (&lval, parser);
2691 SELF_CHECK (token == COMPOUND_ASSIGN);
2692 SELF_CHECK (lval.opcode == BINOP_RSH);
2694 rust_push_back ('=');
2696 token = rustyylex (&lval, parser);
2697 SELF_CHECK (token == '=');
2699 token = rustyylex (&lval, parser);
2700 SELF_CHECK (token == 0);
2703 /* Unit test the lexer. */
2706 rust_lex_tests (void)
2710 // Set up dummy "parser", so that rust_type works.
2711 struct parser_state ps (0, &rust_language_defn, target_gdbarch ());
2712 rust_parser parser (&ps);
2714 rust_lex_test_one (&parser, "", 0);
2715 rust_lex_test_one (&parser, " \t \n \r ", 0);
2716 rust_lex_test_one (&parser, "thread 23", 0);
2717 rust_lex_test_one (&parser, "task 23", 0);
2718 rust_lex_test_one (&parser, "th 104", 0);
2719 rust_lex_test_one (&parser, "ta 97", 0);
2721 rust_lex_int_test (&parser, "'z'", 'z', INTEGER);
2722 rust_lex_int_test (&parser, "'\\xff'", 0xff, INTEGER);
2723 rust_lex_int_test (&parser, "'\\u{1016f}'", 0x1016f, INTEGER);
2724 rust_lex_int_test (&parser, "b'z'", 'z', INTEGER);
2725 rust_lex_int_test (&parser, "b'\\xfe'", 0xfe, INTEGER);
2726 rust_lex_int_test (&parser, "b'\\xFE'", 0xfe, INTEGER);
2727 rust_lex_int_test (&parser, "b'\\xfE'", 0xfe, INTEGER);
2729 /* Test all escapes in both modes. */
2730 rust_lex_int_test (&parser, "'\\n'", '\n', INTEGER);
2731 rust_lex_int_test (&parser, "'\\r'", '\r', INTEGER);
2732 rust_lex_int_test (&parser, "'\\t'", '\t', INTEGER);
2733 rust_lex_int_test (&parser, "'\\\\'", '\\', INTEGER);
2734 rust_lex_int_test (&parser, "'\\0'", '\0', INTEGER);
2735 rust_lex_int_test (&parser, "'\\''", '\'', INTEGER);
2736 rust_lex_int_test (&parser, "'\\\"'", '"', INTEGER);
2738 rust_lex_int_test (&parser, "b'\\n'", '\n', INTEGER);
2739 rust_lex_int_test (&parser, "b'\\r'", '\r', INTEGER);
2740 rust_lex_int_test (&parser, "b'\\t'", '\t', INTEGER);
2741 rust_lex_int_test (&parser, "b'\\\\'", '\\', INTEGER);
2742 rust_lex_int_test (&parser, "b'\\0'", '\0', INTEGER);
2743 rust_lex_int_test (&parser, "b'\\''", '\'', INTEGER);
2744 rust_lex_int_test (&parser, "b'\\\"'", '"', INTEGER);
2746 rust_lex_exception_test (&parser, "'z", "Unterminated character literal");
2747 rust_lex_exception_test (&parser, "b'\\x0'", "Not enough hex digits seen");
2748 rust_lex_exception_test (&parser, "b'\\u{0}'",
2749 "Unicode escape in byte literal");
2750 rust_lex_exception_test (&parser, "'\\x0'", "Not enough hex digits seen");
2751 rust_lex_exception_test (&parser, "'\\u0'", "Missing '{' in Unicode escape");
2752 rust_lex_exception_test (&parser, "'\\u{0", "Missing '}' in Unicode escape");
2753 rust_lex_exception_test (&parser, "'\\u{0000007}", "Overlong hex escape");
2754 rust_lex_exception_test (&parser, "'\\u{}", "Not enough hex digits seen");
2755 rust_lex_exception_test (&parser, "'\\Q'", "Invalid escape \\Q in literal");
2756 rust_lex_exception_test (&parser, "b'\\Q'", "Invalid escape \\Q in literal");
2758 rust_lex_int_test (&parser, "23", 23, DECIMAL_INTEGER);
2759 rust_lex_int_test (&parser, "2_344__29", 234429, INTEGER);
2760 rust_lex_int_test (&parser, "0x1f", 0x1f, INTEGER);
2761 rust_lex_int_test (&parser, "23usize", 23, INTEGER);
2762 rust_lex_int_test (&parser, "23i32", 23, INTEGER);
2763 rust_lex_int_test (&parser, "0x1_f", 0x1f, INTEGER);
2764 rust_lex_int_test (&parser, "0b1_101011__", 0x6b, INTEGER);
2765 rust_lex_int_test (&parser, "0o001177i64", 639, INTEGER);
2767 rust_lex_test_trailing_dot (&parser);
2769 rust_lex_test_one (&parser, "23.", FLOAT);
2770 rust_lex_test_one (&parser, "23.99f32", FLOAT);
2771 rust_lex_test_one (&parser, "23e7", FLOAT);
2772 rust_lex_test_one (&parser, "23E-7", FLOAT);
2773 rust_lex_test_one (&parser, "23e+7", FLOAT);
2774 rust_lex_test_one (&parser, "23.99e+7f64", FLOAT);
2775 rust_lex_test_one (&parser, "23.82f32", FLOAT);
2777 rust_lex_stringish_test (&parser, "hibob", "hibob", IDENT);
2778 rust_lex_stringish_test (&parser, "hibob__93", "hibob__93", IDENT);
2779 rust_lex_stringish_test (&parser, "thread", "thread", IDENT);
2781 rust_lex_stringish_test (&parser, "\"string\"", "string", STRING);
2782 rust_lex_stringish_test (&parser, "\"str\\ting\"", "str\ting", STRING);
2783 rust_lex_stringish_test (&parser, "\"str\\\"ing\"", "str\"ing", STRING);
2784 rust_lex_stringish_test (&parser, "r\"str\\ing\"", "str\\ing", STRING);
2785 rust_lex_stringish_test (&parser, "r#\"str\\ting\"#", "str\\ting", STRING);
2786 rust_lex_stringish_test (&parser, "r###\"str\\\"ing\"###", "str\\\"ing",
2789 rust_lex_stringish_test (&parser, "b\"string\"", "string", BYTESTRING);
2790 rust_lex_stringish_test (&parser, "b\"\x73tring\"", "string", BYTESTRING);
2791 rust_lex_stringish_test (&parser, "b\"str\\\"ing\"", "str\"ing", BYTESTRING);
2792 rust_lex_stringish_test (&parser, "br####\"\\x73tring\"####", "\\x73tring",
2795 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
2796 rust_lex_test_one (&parser, identifier_tokens[i].name,
2797 identifier_tokens[i].value);
2799 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
2800 rust_lex_test_one (&parser, operator_tokens[i].name,
2801 operator_tokens[i].value);
2803 rust_lex_test_completion (&parser);
2804 rust_lex_test_push_back (&parser);
2807 #endif /* GDB_SELF_TEST */
2810 _initialize_rust_exp (void)
2812 int code = regcomp (&number_regex, number_regex_text, REG_EXTENDED);
2813 /* If the regular expression was incorrect, it was a programming
2815 gdb_assert (code == 0);
2818 selftests::register_test ("rust-lex", rust_lex_tests);