1 /* Bison parser for Rust expressions, for GDB.
2 Copyright (C) 2016-2017 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 /* Removing the last conflict seems difficult. */
28 #include "cp-support.h"
29 #include "gdb_obstack.h"
30 #include "gdb_regex.h"
31 #include "rust-lang.h"
32 #include "parser-defs.h"
37 #define GDB_YY_REMAP_PREFIX rust
40 #define RUSTSTYPE YYSTYPE
42 extern initialize_file_ftype _initialize_rust_exp;
45 typedef std::vector<const struct rust_op *> rust_op_vector;
47 /* A typed integer constant. */
55 /* A typed floating point constant. */
57 struct typed_val_float
63 /* An identifier and an expression. This is used to represent one
64 element of a struct initializer. */
69 const struct rust_op *init;
72 typedef std::vector<set_field> rust_set_vector;
74 static int rustyylex (void);
75 static void rust_push_back (char c);
76 static const char *rust_copy_name (const char *, int);
77 static struct stoken rust_concat3 (const char *, const char *, const char *);
78 static struct stoken make_stoken (const char *);
79 static struct block_symbol rust_lookup_symbol (const char *name,
80 const struct block *block,
81 const domain_enum domain);
82 static struct type *rust_lookup_type (const char *name,
83 const struct block *block);
84 static struct type *rust_type (const char *name);
86 static const struct rust_op *crate_name (const struct rust_op *name);
87 static const struct rust_op *super_name (const struct rust_op *name,
88 unsigned int n_supers);
90 static const struct rust_op *ast_operation (enum exp_opcode opcode,
91 const struct rust_op *left,
92 const struct rust_op *right);
93 static const struct rust_op *ast_compound_assignment
94 (enum exp_opcode opcode, const struct rust_op *left,
95 const struct rust_op *rust_op);
96 static const struct rust_op *ast_literal (struct typed_val_int val);
97 static const struct rust_op *ast_dliteral (struct typed_val_float val);
98 static const struct rust_op *ast_structop (const struct rust_op *left,
101 static const struct rust_op *ast_structop_anonymous
102 (const struct rust_op *left, struct typed_val_int number);
103 static const struct rust_op *ast_unary (enum exp_opcode opcode,
104 const struct rust_op *expr);
105 static const struct rust_op *ast_cast (const struct rust_op *expr,
106 const struct rust_op *type);
107 static const struct rust_op *ast_call_ish (enum exp_opcode opcode,
108 const struct rust_op *expr,
109 rust_op_vector *params);
110 static const struct rust_op *ast_path (struct stoken name,
111 rust_op_vector *params);
112 static const struct rust_op *ast_string (struct stoken str);
113 static const struct rust_op *ast_struct (const struct rust_op *name,
114 rust_set_vector *fields);
115 static const struct rust_op *ast_range (const struct rust_op *lhs,
116 const struct rust_op *rhs);
117 static const struct rust_op *ast_array_type (const struct rust_op *lhs,
118 struct typed_val_int val);
119 static const struct rust_op *ast_slice_type (const struct rust_op *type);
120 static const struct rust_op *ast_reference_type (const struct rust_op *type);
121 static const struct rust_op *ast_pointer_type (const struct rust_op *type,
123 static const struct rust_op *ast_function_type (const struct rust_op *result,
124 rust_op_vector *params);
125 static const struct rust_op *ast_tuple_type (rust_op_vector *params);
127 /* The current rust parser. */
130 static rust_parser *current_parser;
132 /* A regular expression for matching Rust numbers. This is split up
133 since it is very long and this gives us a way to comment the
136 static const char *number_regex_text =
137 /* subexpression 1: allows use of alternation, otherwise uninteresting */
139 /* First comes floating point. */
140 /* Recognize number after the decimal point, with optional
141 exponent and optional type suffix.
142 subexpression 2: allows "?", otherwise uninteresting
143 subexpression 3: if present, type suffix
145 "[0-9][0-9_]*\\.[0-9][0-9_]*([eE][-+]?[0-9][0-9_]*)?(f32|f64)?"
146 #define FLOAT_TYPE1 3
148 /* Recognize exponent without decimal point, with optional type
150 subexpression 4: if present, type suffix
152 #define FLOAT_TYPE2 4
153 "[0-9][0-9_]*[eE][-+]?[0-9][0-9_]*(f32|f64)?"
155 /* "23." is a valid floating point number, but "23.e5" and
156 "23.f32" are not. So, handle the trailing-. case
160 /* Finally come integers.
161 subexpression 5: text of integer
162 subexpression 6: if present, type suffix
163 subexpression 7: allows use of alternation, otherwise uninteresting
167 "(0x[a-fA-F0-9_]+|0o[0-7_]+|0b[01_]+|[0-9][0-9_]*)"
168 "([iu](size|8|16|32|64))?"
170 /* The number of subexpressions to allocate space for, including the
171 "0th" whole match subexpression. */
172 #define NUM_SUBEXPRESSIONS 8
174 /* The compiled number-matching regex. */
176 static regex_t number_regex;
178 /* True if we're running unit tests. */
180 static int unit_testing;
182 /* Obstack for data temporarily allocated during parsing. Points to
183 the obstack in the rust_parser, or to a temporary obstack during
186 static auto_obstack *work_obstack;
188 /* An instance of this is created before parsing, and destroyed when
189 parsing is finished. */
193 rust_parser (struct parser_state *state)
194 : rust_ast (nullptr),
197 gdb_assert (current_parser == nullptr);
198 current_parser = this;
199 work_obstack = &obstack;
204 /* Clean up the globals we set. */
205 current_parser = nullptr;
206 work_obstack = nullptr;
209 /* Create a new rust_set_vector. The storage for the new vector is
210 managed by this class. */
211 rust_set_vector *new_set_vector ()
213 rust_set_vector *result = new rust_set_vector;
214 set_vectors.push_back (std::unique_ptr<rust_set_vector> (result));
218 /* Create a new rust_ops_vector. The storage for the new vector is
219 managed by this class. */
220 rust_op_vector *new_op_vector ()
222 rust_op_vector *result = new rust_op_vector;
223 op_vectors.push_back (std::unique_ptr<rust_op_vector> (result));
227 /* Return the parser's language. */
228 const struct language_defn *language () const
230 return parse_language (pstate);
233 /* Return the parser's gdbarch. */
234 struct gdbarch *arch () const
236 return parse_gdbarch (pstate);
239 /* A pointer to this is installed globally. */
240 auto_obstack obstack;
242 /* Result of parsing. Points into obstack. */
243 const struct rust_op *rust_ast;
245 /* This keeps track of the various vectors we allocate. */
246 std::vector<std::unique_ptr<rust_set_vector>> set_vectors;
247 std::vector<std::unique_ptr<rust_op_vector>> op_vectors;
249 /* The parser state gdb gave us. */
250 struct parser_state *pstate;
257 /* A typed integer constant. */
258 struct typed_val_int typed_val_int;
260 /* A typed floating point constant. */
261 struct typed_val_float typed_val_float;
263 /* An identifier or string. */
266 /* A token representing an opcode, like "==". */
267 enum exp_opcode opcode;
269 /* A list of expressions; for example, the arguments to a function
271 rust_op_vector *params;
273 /* A list of field initializers. */
274 rust_set_vector *field_inits;
276 /* A single field initializer. */
277 struct set_field one_field_init;
280 const struct rust_op *op;
282 /* A plain integer, for example used to count the number of
283 "super::" prefixes on a path. */
289 /* Rust AST operations. We build a tree of these; then lower them
290 to gdb expressions when parsing has completed. */
295 enum exp_opcode opcode;
296 /* If OPCODE is OP_TYPE, then this holds information about what type
297 is described by this node. */
298 enum type_code typecode;
299 /* Indicates whether OPCODE actually represents a compound
300 assignment. For example, if OPCODE is GTGT and this is false,
301 then this rust_op represents an ordinary ">>"; but if this is
302 true, then this rust_op represents ">>=". Unused in other
304 unsigned int compound_assignment : 1;
305 /* Only used by a field expression; if set, indicates that the field
306 name occurred at the end of the expression and is eligible for
308 unsigned int completing : 1;
309 /* Operands of expression. Which one is used and how depends on the
310 particular opcode. */
319 %token <sval> COMPLETE
320 %token <typed_val_int> INTEGER
321 %token <typed_val_int> DECIMAL_INTEGER
323 %token <sval> BYTESTRING
324 %token <typed_val_float> FLOAT
325 %token <opcode> COMPOUND_ASSIGN
327 /* Keyword tokens. */
328 %token <voidval> KW_AS
329 %token <voidval> KW_IF
330 %token <voidval> KW_TRUE
331 %token <voidval> KW_FALSE
332 %token <voidval> KW_SUPER
333 %token <voidval> KW_SELF
334 %token <voidval> KW_MUT
335 %token <voidval> KW_EXTERN
336 %token <voidval> KW_CONST
337 %token <voidval> KW_FN
338 %token <voidval> KW_SIZEOF
340 /* Operator tokens. */
341 %token <voidval> DOTDOT
342 %token <voidval> OROR
343 %token <voidval> ANDAND
344 %token <voidval> EQEQ
345 %token <voidval> NOTEQ
346 %token <voidval> LTEQ
347 %token <voidval> GTEQ
348 %token <voidval> LSH RSH
349 %token <voidval> COLONCOLON
350 %token <voidval> ARROW
353 %type <op> path_for_expr
354 %type <op> identifier_path_for_expr
355 %type <op> path_for_type
356 %type <op> identifier_path_for_type
357 %type <op> just_identifiers_for_type
359 %type <params> maybe_type_list
360 %type <params> type_list
362 %type <depth> super_path
366 %type <op> field_expr
369 %type <op> binop_expr
370 %type <op> binop_expr_expr
371 %type <op> type_cast_expr
372 %type <op> assignment_expr
373 %type <op> compound_assignment_expr
374 %type <op> paren_expr
377 %type <op> tuple_expr
379 %type <op> struct_expr
380 %type <op> array_expr
381 %type <op> range_expr
383 %type <params> expr_list
384 %type <params> maybe_expr_list
385 %type <params> paren_expr_list
387 %type <field_inits> struct_expr_list
388 %type <one_field_init> struct_expr_tail
392 %right '=' COMPOUND_ASSIGN
395 %nonassoc EQEQ NOTEQ '<' '>' LTEQ GTEQ
403 /* These could be %precedence in Bison, but that isn't a yacc
414 /* If we are completing and see a valid parse,
415 rust_ast will already have been set. */
416 if (current_parser->rust_ast == NULL)
417 current_parser->rust_ast = $1;
421 /* Note that the Rust grammar includes a method_call_expr, but we
422 handle this differently, to avoid a shift/reduce conflict with
434 | unop_expr /* Must precede call_expr because of ambiguity with sizeof. */
441 '(' expr ',' maybe_expr_list ')'
444 error (_("Tuple expressions not supported yet"));
451 struct typed_val_int val;
454 = language_lookup_primitive_type (current_parser->language (),
455 current_parser->arch (),
458 $$ = ast_literal (val);
462 /* To avoid a shift/reduce conflict with call_expr, we don't handle
463 tuple struct expressions here, but instead when examining the
466 path_for_expr '{' struct_expr_list '}'
467 { $$ = ast_struct ($1, $3); }
494 $$ = current_parser->new_set_vector ();
498 rust_set_vector *result = current_parser->new_set_vector ();
499 result->push_back ($1);
502 | IDENT ':' expr ',' struct_expr_list
514 '[' KW_MUT expr_list ']'
515 { $$ = ast_call_ish (OP_ARRAY, NULL, $3); }
517 { $$ = ast_call_ish (OP_ARRAY, NULL, $2); }
518 | '[' KW_MUT expr ';' expr ']'
519 { $$ = ast_operation (OP_RUST_ARRAY, $3, $5); }
520 | '[' expr ';' expr ']'
521 { $$ = ast_operation (OP_RUST_ARRAY, $2, $4); }
526 { $$ = ast_range ($1, NULL); }
528 { $$ = ast_range ($1, $3); }
530 { $$ = ast_range (NULL, $2); }
532 { $$ = ast_range (NULL, NULL); }
537 { $$ = ast_literal ($1); }
539 { $$ = ast_literal ($1); }
541 { $$ = ast_dliteral ($1); }
544 const struct rust_op *str = ast_string ($1);
545 struct set_field field;
546 struct typed_val_int val;
549 rust_set_vector *fields = current_parser->new_set_vector ();
551 /* Wrap the raw string in the &str struct. */
552 field.name.ptr = "data_ptr";
553 field.name.length = strlen (field.name.ptr);
554 field.init = ast_unary (UNOP_ADDR, ast_string ($1));
555 fields->push_back (field);
557 val.type = rust_type ("usize");
560 field.name.ptr = "length";
561 field.name.length = strlen (field.name.ptr);
562 field.init = ast_literal (val);
563 fields->push_back (field);
566 token.length = strlen (token.ptr);
567 $$ = ast_struct (ast_path (token, NULL), fields);
570 { $$ = ast_string ($1); }
573 struct typed_val_int val;
575 val.type = language_bool_type (current_parser->language (),
576 current_parser->arch ());
578 $$ = ast_literal (val);
582 struct typed_val_int val;
584 val.type = language_bool_type (current_parser->language (),
585 current_parser->arch ());
587 $$ = ast_literal (val);
593 { $$ = ast_structop ($1, $3.ptr, 0); }
596 $$ = ast_structop ($1, $3.ptr, 1);
597 current_parser->rust_ast = $$;
599 | expr '.' DECIMAL_INTEGER
600 { $$ = ast_structop_anonymous ($1, $3); }
605 { $$ = ast_operation (BINOP_SUBSCRIPT, $1, $3); }
610 { $$ = ast_unary (UNOP_PLUS, $2); }
612 | '-' expr %prec UNARY
613 { $$ = ast_unary (UNOP_NEG, $2); }
615 | '!' expr %prec UNARY
617 /* Note that we provide a Rust-specific evaluator
618 override for UNOP_COMPLEMENT, so it can do the
619 right thing for both bool and integral
621 $$ = ast_unary (UNOP_COMPLEMENT, $2);
624 | '*' expr %prec UNARY
625 { $$ = ast_unary (UNOP_IND, $2); }
627 | '&' expr %prec UNARY
628 { $$ = ast_unary (UNOP_ADDR, $2); }
630 | '&' KW_MUT expr %prec UNARY
631 { $$ = ast_unary (UNOP_ADDR, $3); }
632 | KW_SIZEOF '(' expr ')' %prec UNARY
633 { $$ = ast_unary (UNOP_SIZEOF, $3); }
640 | compound_assignment_expr
645 { $$ = ast_operation (BINOP_MUL, $1, $3); }
648 { $$ = ast_operation (BINOP_REPEAT, $1, $3); }
651 { $$ = ast_operation (BINOP_DIV, $1, $3); }
654 { $$ = ast_operation (BINOP_REM, $1, $3); }
657 { $$ = ast_operation (BINOP_LESS, $1, $3); }
660 { $$ = ast_operation (BINOP_GTR, $1, $3); }
663 { $$ = ast_operation (BINOP_BITWISE_AND, $1, $3); }
666 { $$ = ast_operation (BINOP_BITWISE_IOR, $1, $3); }
669 { $$ = ast_operation (BINOP_BITWISE_XOR, $1, $3); }
672 { $$ = ast_operation (BINOP_ADD, $1, $3); }
675 { $$ = ast_operation (BINOP_SUB, $1, $3); }
678 { $$ = ast_operation (BINOP_LOGICAL_OR, $1, $3); }
681 { $$ = ast_operation (BINOP_LOGICAL_AND, $1, $3); }
684 { $$ = ast_operation (BINOP_EQUAL, $1, $3); }
687 { $$ = ast_operation (BINOP_NOTEQUAL, $1, $3); }
690 { $$ = ast_operation (BINOP_LEQ, $1, $3); }
693 { $$ = ast_operation (BINOP_GEQ, $1, $3); }
696 { $$ = ast_operation (BINOP_LSH, $1, $3); }
699 { $$ = ast_operation (BINOP_RSH, $1, $3); }
704 { $$ = ast_cast ($1, $3); }
709 { $$ = ast_operation (BINOP_ASSIGN, $1, $3); }
712 compound_assignment_expr:
713 expr COMPOUND_ASSIGN expr
714 { $$ = ast_compound_assignment ($2, $1, $3); }
726 $$ = current_parser->new_op_vector ();
739 /* The result can't be NULL. */
740 $$ = current_parser->new_op_vector ();
755 { $$ = ast_call_ish (OP_FUNCALL, $1, $2); }
766 | super_path KW_SUPER COLONCOLON
774 { $$ = ast_path ($1, NULL); }
776 { $$ = ast_path (make_stoken ("self"), NULL); }
780 identifier_path_for_expr
781 | KW_SELF COLONCOLON identifier_path_for_expr
782 { $$ = super_name ($3, 0); }
783 | maybe_self_path super_path identifier_path_for_expr
784 { $$ = super_name ($3, $2); }
785 | COLONCOLON identifier_path_for_expr
786 { $$ = crate_name ($2); }
787 | KW_EXTERN identifier_path_for_expr
789 /* This is a gdb extension to make it possible to
790 refer to items in other crates. It just bypasses
791 adding the current crate to the front of the
793 $$ = ast_path (rust_concat3 ("::", $2->left.sval.ptr, NULL),
798 identifier_path_for_expr:
800 { $$ = ast_path ($1, NULL); }
801 | identifier_path_for_expr COLONCOLON IDENT
803 $$ = ast_path (rust_concat3 ($1->left.sval.ptr, "::",
807 | identifier_path_for_expr COLONCOLON '<' type_list '>'
808 { $$ = ast_path ($1->left.sval, $4); }
809 | identifier_path_for_expr COLONCOLON '<' type_list RSH
811 $$ = ast_path ($1->left.sval, $4);
812 rust_push_back ('>');
817 identifier_path_for_type
818 | KW_SELF COLONCOLON identifier_path_for_type
819 { $$ = super_name ($3, 0); }
820 | maybe_self_path super_path identifier_path_for_type
821 { $$ = super_name ($3, $2); }
822 | COLONCOLON identifier_path_for_type
823 { $$ = crate_name ($2); }
824 | KW_EXTERN identifier_path_for_type
826 /* This is a gdb extension to make it possible to
827 refer to items in other crates. It just bypasses
828 adding the current crate to the front of the
830 $$ = ast_path (rust_concat3 ("::", $2->left.sval.ptr, NULL),
835 just_identifiers_for_type:
837 { $$ = ast_path ($1, NULL); }
838 | just_identifiers_for_type COLONCOLON IDENT
840 $$ = ast_path (rust_concat3 ($1->left.sval.ptr, "::",
846 identifier_path_for_type:
847 just_identifiers_for_type
848 | just_identifiers_for_type '<' type_list '>'
849 { $$ = ast_path ($1->left.sval, $3); }
850 | just_identifiers_for_type '<' type_list RSH
852 $$ = ast_path ($1->left.sval, $3);
853 rust_push_back ('>');
859 | '[' type ';' INTEGER ']'
860 { $$ = ast_array_type ($2, $4); }
861 | '[' type ';' DECIMAL_INTEGER ']'
862 { $$ = ast_array_type ($2, $4); }
864 { $$ = ast_slice_type ($3); }
866 { $$ = ast_reference_type ($2); }
868 { $$ = ast_pointer_type ($3, 1); }
870 { $$ = ast_pointer_type ($3, 0); }
871 | KW_FN '(' maybe_type_list ')' ARROW type
872 { $$ = ast_function_type ($6, $3); }
873 | '(' maybe_type_list ')'
874 { $$ = ast_tuple_type ($2); }
887 rust_op_vector *result = current_parser->new_op_vector ();
888 result->push_back ($1);
900 /* A struct of this type is used to describe a token. */
906 enum exp_opcode opcode;
909 /* Identifier tokens. */
911 static const struct token_info identifier_tokens[] =
913 { "as", KW_AS, OP_NULL },
914 { "false", KW_FALSE, OP_NULL },
915 { "if", 0, OP_NULL },
916 { "mut", KW_MUT, OP_NULL },
917 { "const", KW_CONST, OP_NULL },
918 { "self", KW_SELF, OP_NULL },
919 { "super", KW_SUPER, OP_NULL },
920 { "true", KW_TRUE, OP_NULL },
921 { "extern", KW_EXTERN, OP_NULL },
922 { "fn", KW_FN, OP_NULL },
923 { "sizeof", KW_SIZEOF, OP_NULL },
926 /* Operator tokens, sorted longest first. */
928 static const struct token_info operator_tokens[] =
930 { ">>=", COMPOUND_ASSIGN, BINOP_RSH },
931 { "<<=", COMPOUND_ASSIGN, BINOP_LSH },
933 { "<<", LSH, OP_NULL },
934 { ">>", RSH, OP_NULL },
935 { "&&", ANDAND, OP_NULL },
936 { "||", OROR, OP_NULL },
937 { "==", EQEQ, OP_NULL },
938 { "!=", NOTEQ, OP_NULL },
939 { "<=", LTEQ, OP_NULL },
940 { ">=", GTEQ, OP_NULL },
941 { "+=", COMPOUND_ASSIGN, BINOP_ADD },
942 { "-=", COMPOUND_ASSIGN, BINOP_SUB },
943 { "*=", COMPOUND_ASSIGN, BINOP_MUL },
944 { "/=", COMPOUND_ASSIGN, BINOP_DIV },
945 { "%=", COMPOUND_ASSIGN, BINOP_REM },
946 { "&=", COMPOUND_ASSIGN, BINOP_BITWISE_AND },
947 { "|=", COMPOUND_ASSIGN, BINOP_BITWISE_IOR },
948 { "^=", COMPOUND_ASSIGN, BINOP_BITWISE_XOR },
950 { "::", COLONCOLON, OP_NULL },
951 { "..", DOTDOT, OP_NULL },
952 { "->", ARROW, OP_NULL }
955 /* Helper function to copy to the name obstack. */
958 rust_copy_name (const char *name, int len)
960 return (const char *) obstack_copy0 (work_obstack, name, len);
963 /* Helper function to make an stoken from a C string. */
966 make_stoken (const char *p)
968 struct stoken result;
971 result.length = strlen (result.ptr);
975 /* Helper function to concatenate three strings on the name
979 rust_concat3 (const char *s1, const char *s2, const char *s3)
981 return make_stoken (obconcat (work_obstack, s1, s2, s3, (char *) NULL));
984 /* Return an AST node referring to NAME, but relative to the crate's
987 static const struct rust_op *
988 crate_name (const struct rust_op *name)
990 std::string crate = rust_crate_for_block (expression_context_block);
991 struct stoken result;
993 gdb_assert (name->opcode == OP_VAR_VALUE);
996 error (_("Could not find crate for current location"));
997 result = make_stoken (obconcat (work_obstack, "::", crate.c_str (), "::",
998 name->left.sval.ptr, (char *) NULL));
1000 return ast_path (result, name->right.params);
1003 /* Create an AST node referring to a "super::" qualified name. IDENT
1004 is the base name and N_SUPERS is how many "super::"s were
1005 provided. N_SUPERS can be zero. */
1007 static const struct rust_op *
1008 super_name (const struct rust_op *ident, unsigned int n_supers)
1010 const char *scope = block_scope (expression_context_block);
1013 gdb_assert (ident->opcode == OP_VAR_VALUE);
1015 if (scope[0] == '\0')
1016 error (_("Couldn't find namespace scope for self::"));
1022 std::vector<int> offsets;
1023 unsigned int current_len;
1025 current_len = cp_find_first_component (scope);
1026 while (scope[current_len] != '\0')
1028 offsets.push_back (current_len);
1029 gdb_assert (scope[current_len] == ':');
1032 current_len += cp_find_first_component (scope
1036 len = offsets.size ();
1037 if (n_supers >= len)
1038 error (_("Too many super:: uses from '%s'"), scope);
1040 offset = offsets[len - n_supers];
1043 offset = strlen (scope);
1045 obstack_grow (work_obstack, "::", 2);
1046 obstack_grow (work_obstack, scope, offset);
1047 obstack_grow (work_obstack, "::", 2);
1048 obstack_grow0 (work_obstack, ident->left.sval.ptr, ident->left.sval.length);
1050 return ast_path (make_stoken ((const char *) obstack_finish (work_obstack)),
1051 ident->right.params);
1054 /* A helper that updates innermost_block as appropriate. */
1057 update_innermost_block (struct block_symbol sym)
1059 if (symbol_read_needs_frame (sym.symbol)
1060 && (innermost_block == NULL
1061 || contained_in (sym.block, innermost_block)))
1062 innermost_block = sym.block;
1065 /* A helper to look up a Rust type, or fail. This only works for
1066 types defined by rust_language_arch_info. */
1068 static struct type *
1069 rust_type (const char *name)
1073 /* When unit testing, we don't bother checking the types, so avoid a
1074 possibly-failing lookup here. */
1078 type = language_lookup_primitive_type (current_parser->language (),
1079 current_parser->arch (),
1082 error (_("Could not find Rust type %s"), name);
1086 /* Lex a hex number with at least MIN digits and at most MAX
1090 lex_hex (int min, int max)
1092 uint32_t result = 0;
1094 /* We only want to stop at MAX if we're lexing a byte escape. */
1095 int check_max = min == max;
1097 while ((check_max ? len <= max : 1)
1098 && ((lexptr[0] >= 'a' && lexptr[0] <= 'f')
1099 || (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1100 || (lexptr[0] >= '0' && lexptr[0] <= '9')))
1103 if (lexptr[0] >= 'a' && lexptr[0] <= 'f')
1104 result = result + 10 + lexptr[0] - 'a';
1105 else if (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1106 result = result + 10 + lexptr[0] - 'A';
1108 result = result + lexptr[0] - '0';
1114 error (_("Not enough hex digits seen"));
1117 gdb_assert (min != max);
1118 error (_("Overlong hex escape"));
1124 /* Lex an escape. IS_BYTE is true if we're lexing a byte escape;
1125 otherwise we're lexing a character escape. */
1128 lex_escape (int is_byte)
1132 gdb_assert (lexptr[0] == '\\');
1138 result = lex_hex (2, 2);
1143 error (_("Unicode escape in byte literal"));
1145 if (lexptr[0] != '{')
1146 error (_("Missing '{' in Unicode escape"));
1148 result = lex_hex (1, 6);
1149 /* Could do range checks here. */
1150 if (lexptr[0] != '}')
1151 error (_("Missing '}' in Unicode escape"));
1185 error (_("Invalid escape \\%c in literal"), lexptr[0]);
1191 /* Lex a character constant. */
1194 lex_character (void)
1199 if (lexptr[0] == 'b')
1204 gdb_assert (lexptr[0] == '\'');
1206 /* This should handle UTF-8 here. */
1207 if (lexptr[0] == '\\')
1208 value = lex_escape (is_byte);
1211 value = lexptr[0] & 0xff;
1215 if (lexptr[0] != '\'')
1216 error (_("Unterminated character literal"));
1219 rustyylval.typed_val_int.val = value;
1220 rustyylval.typed_val_int.type = rust_type (is_byte ? "u8" : "char");
1225 /* Return the offset of the double quote if STR looks like the start
1226 of a raw string, or 0 if STR does not start a raw string. */
1229 starts_raw_string (const char *str)
1231 const char *save = str;
1236 while (str[0] == '#')
1243 /* Return true if STR looks like the end of a raw string that had N
1244 hashes at the start. */
1247 ends_raw_string (const char *str, int n)
1251 gdb_assert (str[0] == '"');
1252 for (i = 0; i < n; ++i)
1253 if (str[i + 1] != '#')
1258 /* Lex a string constant. */
1263 int is_byte = lexptr[0] == 'b';
1265 int len_in_chars = 0;
1269 raw_length = starts_raw_string (lexptr);
1270 lexptr += raw_length;
1271 gdb_assert (lexptr[0] == '"');
1280 if (lexptr[0] == '"' && ends_raw_string (lexptr, raw_length - 1))
1282 /* Exit with lexptr pointing after the final "#". */
1283 lexptr += raw_length;
1286 else if (lexptr[0] == '\0')
1287 error (_("Unexpected EOF in string"));
1289 value = lexptr[0] & 0xff;
1290 if (is_byte && value > 127)
1291 error (_("Non-ASCII value in raw byte string"));
1292 obstack_1grow (work_obstack, value);
1296 else if (lexptr[0] == '"')
1298 /* Make sure to skip the quote. */
1302 else if (lexptr[0] == '\\')
1304 value = lex_escape (is_byte);
1307 obstack_1grow (work_obstack, value);
1309 convert_between_encodings ("UTF-32", "UTF-8", (gdb_byte *) &value,
1310 sizeof (value), sizeof (value),
1311 work_obstack, translit_none);
1313 else if (lexptr[0] == '\0')
1314 error (_("Unexpected EOF in string"));
1317 value = lexptr[0] & 0xff;
1318 if (is_byte && value > 127)
1319 error (_("Non-ASCII value in byte string"));
1320 obstack_1grow (work_obstack, value);
1325 rustyylval.sval.length = obstack_object_size (work_obstack);
1326 rustyylval.sval.ptr = (const char *) obstack_finish (work_obstack);
1327 return is_byte ? BYTESTRING : STRING;
1330 /* Return true if STRING starts with whitespace followed by a digit. */
1333 space_then_number (const char *string)
1335 const char *p = string;
1337 while (p[0] == ' ' || p[0] == '\t')
1342 return *p >= '0' && *p <= '9';
1345 /* Return true if C can start an identifier. */
1348 rust_identifier_start_p (char c)
1350 return ((c >= 'a' && c <= 'z')
1351 || (c >= 'A' && c <= 'Z')
1356 /* Lex an identifier. */
1359 lex_identifier (void)
1361 const char *start = lexptr;
1362 unsigned int length;
1363 const struct token_info *token;
1365 int is_gdb_var = lexptr[0] == '$';
1367 gdb_assert (rust_identifier_start_p (lexptr[0]));
1371 /* For the time being this doesn't handle Unicode rules. Non-ASCII
1372 identifiers are gated anyway. */
1373 while ((lexptr[0] >= 'a' && lexptr[0] <= 'z')
1374 || (lexptr[0] >= 'A' && lexptr[0] <= 'Z')
1376 || (is_gdb_var && lexptr[0] == '$')
1377 || (lexptr[0] >= '0' && lexptr[0] <= '9'))
1381 length = lexptr - start;
1383 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
1385 if (length == strlen (identifier_tokens[i].name)
1386 && strncmp (identifier_tokens[i].name, start, length) == 0)
1388 token = &identifier_tokens[i];
1395 if (token->value == 0)
1397 /* Leave the terminating token alone. */
1402 else if (token == NULL
1403 && (strncmp (start, "thread", length) == 0
1404 || strncmp (start, "task", length) == 0)
1405 && space_then_number (lexptr))
1407 /* "task" or "thread" followed by a number terminates the
1408 parse, per gdb rules. */
1413 if (token == NULL || (parse_completion && lexptr[0] == '\0'))
1414 rustyylval.sval = make_stoken (rust_copy_name (start, length));
1416 if (parse_completion && lexptr[0] == '\0')
1418 /* Prevent rustyylex from returning two COMPLETE tokens. */
1419 prev_lexptr = lexptr;
1424 return token->value;
1430 /* Lex an operator. */
1435 const struct token_info *token = NULL;
1438 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
1440 if (strncmp (operator_tokens[i].name, lexptr,
1441 strlen (operator_tokens[i].name)) == 0)
1443 lexptr += strlen (operator_tokens[i].name);
1444 token = &operator_tokens[i];
1451 rustyylval.opcode = token->opcode;
1452 return token->value;
1463 regmatch_t subexps[NUM_SUBEXPRESSIONS];
1466 int could_be_decimal = 1;
1467 int implicit_i32 = 0;
1468 const char *type_name = NULL;
1471 int type_index = -1;
1474 match = regexec (&number_regex, lexptr, ARRAY_SIZE (subexps), subexps, 0);
1475 /* Failure means the regexp is broken. */
1476 gdb_assert (match == 0);
1478 if (subexps[INT_TEXT].rm_so != -1)
1480 /* Integer part matched. */
1482 end_index = subexps[INT_TEXT].rm_eo;
1483 if (subexps[INT_TYPE].rm_so == -1)
1490 type_index = INT_TYPE;
1491 could_be_decimal = 0;
1494 else if (subexps[FLOAT_TYPE1].rm_so != -1)
1496 /* Found floating point type suffix. */
1497 end_index = subexps[FLOAT_TYPE1].rm_so;
1498 type_index = FLOAT_TYPE1;
1500 else if (subexps[FLOAT_TYPE2].rm_so != -1)
1502 /* Found floating point type suffix. */
1503 end_index = subexps[FLOAT_TYPE2].rm_so;
1504 type_index = FLOAT_TYPE2;
1508 /* Any other floating point match. */
1509 end_index = subexps[0].rm_eo;
1513 /* We need a special case if the final character is ".". In this
1514 case we might need to parse an integer. For example, "23.f()" is
1515 a request for a trait method call, not a syntax error involving
1516 the floating point number "23.". */
1517 gdb_assert (subexps[0].rm_eo > 0);
1518 if (lexptr[subexps[0].rm_eo - 1] == '.')
1520 const char *next = skip_spaces_const (&lexptr[subexps[0].rm_eo]);
1522 if (rust_identifier_start_p (*next) || *next == '.')
1526 end_index = subexps[0].rm_eo;
1528 could_be_decimal = 1;
1533 /* Compute the type name if we haven't already. */
1534 std::string type_name_holder;
1535 if (type_name == NULL)
1537 gdb_assert (type_index != -1);
1538 type_name_holder = std::string (lexptr + subexps[type_index].rm_so,
1539 (subexps[type_index].rm_eo
1540 - subexps[type_index].rm_so));
1541 type_name = type_name_holder.c_str ();
1544 /* Look up the type. */
1545 type = rust_type (type_name);
1547 /* Copy the text of the number and remove the "_"s. */
1549 for (i = 0; i < end_index && lexptr[i]; ++i)
1551 if (lexptr[i] == '_')
1552 could_be_decimal = 0;
1554 number.push_back (lexptr[i]);
1557 /* Advance past the match. */
1558 lexptr += subexps[0].rm_eo;
1560 /* Parse the number. */
1567 if (number[0] == '0')
1569 if (number[1] == 'x')
1571 else if (number[1] == 'o')
1573 else if (number[1] == 'b')
1578 could_be_decimal = 0;
1582 value = strtoul (number.c_str () + offset, NULL, radix);
1583 if (implicit_i32 && value >= ((uint64_t) 1) << 31)
1584 type = rust_type ("i64");
1586 rustyylval.typed_val_int.val = value;
1587 rustyylval.typed_val_int.type = type;
1591 rustyylval.typed_val_float.dval = strtod (number.c_str (), NULL);
1592 rustyylval.typed_val_float.type = type;
1595 return is_integer ? (could_be_decimal ? DECIMAL_INTEGER : INTEGER) : FLOAT;
1603 /* Skip all leading whitespace. */
1604 while (lexptr[0] == ' ' || lexptr[0] == '\t' || lexptr[0] == '\r'
1605 || lexptr[0] == '\n')
1608 /* If we hit EOF and we're completing, then return COMPLETE -- maybe
1609 we're completing an empty string at the end of a field_expr.
1610 But, we don't want to return two COMPLETE tokens in a row. */
1611 if (lexptr[0] == '\0' && lexptr == prev_lexptr)
1613 prev_lexptr = lexptr;
1614 if (lexptr[0] == '\0')
1616 if (parse_completion)
1618 rustyylval.sval = make_stoken ("");
1624 if (lexptr[0] >= '0' && lexptr[0] <= '9')
1625 return lex_number ();
1626 else if (lexptr[0] == 'b' && lexptr[1] == '\'')
1627 return lex_character ();
1628 else if (lexptr[0] == 'b' && lexptr[1] == '"')
1629 return lex_string ();
1630 else if (lexptr[0] == 'b' && starts_raw_string (lexptr + 1))
1631 return lex_string ();
1632 else if (starts_raw_string (lexptr))
1633 return lex_string ();
1634 else if (rust_identifier_start_p (lexptr[0]))
1635 return lex_identifier ();
1636 else if (lexptr[0] == '"')
1637 return lex_string ();
1638 else if (lexptr[0] == '\'')
1639 return lex_character ();
1640 else if (lexptr[0] == '}' || lexptr[0] == ']')
1642 /* Falls through to lex_operator. */
1645 else if (lexptr[0] == '(' || lexptr[0] == '{')
1647 /* Falls through to lex_operator. */
1650 else if (lexptr[0] == ',' && comma_terminates && paren_depth == 0)
1653 return lex_operator ();
1656 /* Push back a single character to be re-lexed. */
1659 rust_push_back (char c)
1661 /* Can't be called before any lexing. */
1662 gdb_assert (prev_lexptr != NULL);
1665 gdb_assert (*lexptr == c);
1670 /* Make an arbitrary operation and fill in the fields. */
1672 static const struct rust_op *
1673 ast_operation (enum exp_opcode opcode, const struct rust_op *left,
1674 const struct rust_op *right)
1676 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1678 result->opcode = opcode;
1679 result->left.op = left;
1680 result->right.op = right;
1685 /* Make a compound assignment operation. */
1687 static const struct rust_op *
1688 ast_compound_assignment (enum exp_opcode opcode, const struct rust_op *left,
1689 const struct rust_op *right)
1691 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1693 result->opcode = opcode;
1694 result->compound_assignment = 1;
1695 result->left.op = left;
1696 result->right.op = right;
1701 /* Make a typed integer literal operation. */
1703 static const struct rust_op *
1704 ast_literal (struct typed_val_int val)
1706 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1708 result->opcode = OP_LONG;
1709 result->left.typed_val_int = val;
1714 /* Make a typed floating point literal operation. */
1716 static const struct rust_op *
1717 ast_dliteral (struct typed_val_float val)
1719 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1721 result->opcode = OP_DOUBLE;
1722 result->left.typed_val_float = val;
1727 /* Make a unary operation. */
1729 static const struct rust_op *
1730 ast_unary (enum exp_opcode opcode, const struct rust_op *expr)
1732 return ast_operation (opcode, expr, NULL);
1735 /* Make a cast operation. */
1737 static const struct rust_op *
1738 ast_cast (const struct rust_op *expr, const struct rust_op *type)
1740 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1742 result->opcode = UNOP_CAST;
1743 result->left.op = expr;
1744 result->right.op = type;
1749 /* Make a call-like operation. This is nominally a function call, but
1750 when lowering we may discover that it actually represents the
1751 creation of a tuple struct. */
1753 static const struct rust_op *
1754 ast_call_ish (enum exp_opcode opcode, const struct rust_op *expr,
1755 rust_op_vector *params)
1757 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1759 result->opcode = opcode;
1760 result->left.op = expr;
1761 result->right.params = params;
1766 /* Make a structure creation operation. */
1768 static const struct rust_op *
1769 ast_struct (const struct rust_op *name, rust_set_vector *fields)
1771 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1773 result->opcode = OP_AGGREGATE;
1774 result->left.op = name;
1775 result->right.field_inits = fields;
1780 /* Make an identifier path. */
1782 static const struct rust_op *
1783 ast_path (struct stoken path, rust_op_vector *params)
1785 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1787 result->opcode = OP_VAR_VALUE;
1788 result->left.sval = path;
1789 result->right.params = params;
1794 /* Make a string constant operation. */
1796 static const struct rust_op *
1797 ast_string (struct stoken str)
1799 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1801 result->opcode = OP_STRING;
1802 result->left.sval = str;
1807 /* Make a field expression. */
1809 static const struct rust_op *
1810 ast_structop (const struct rust_op *left, const char *name, int completing)
1812 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1814 result->opcode = STRUCTOP_STRUCT;
1815 result->completing = completing;
1816 result->left.op = left;
1817 result->right.sval = make_stoken (name);
1822 /* Make an anonymous struct operation, like 'x.0'. */
1824 static const struct rust_op *
1825 ast_structop_anonymous (const struct rust_op *left,
1826 struct typed_val_int number)
1828 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1830 result->opcode = STRUCTOP_ANONYMOUS;
1831 result->left.op = left;
1832 result->right.typed_val_int = number;
1837 /* Make a range operation. */
1839 static const struct rust_op *
1840 ast_range (const struct rust_op *lhs, const struct rust_op *rhs)
1842 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1844 result->opcode = OP_RANGE;
1845 result->left.op = lhs;
1846 result->right.op = rhs;
1851 /* A helper function to make a type-related AST node. */
1853 static struct rust_op *
1854 ast_basic_type (enum type_code typecode)
1856 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1858 result->opcode = OP_TYPE;
1859 result->typecode = typecode;
1863 /* Create an AST node describing an array type. */
1865 static const struct rust_op *
1866 ast_array_type (const struct rust_op *lhs, struct typed_val_int val)
1868 struct rust_op *result = ast_basic_type (TYPE_CODE_ARRAY);
1870 result->left.op = lhs;
1871 result->right.typed_val_int = val;
1875 /* Create an AST node describing a reference type. */
1877 static const struct rust_op *
1878 ast_slice_type (const struct rust_op *type)
1880 /* Use TYPE_CODE_COMPLEX just because it is handy. */
1881 struct rust_op *result = ast_basic_type (TYPE_CODE_COMPLEX);
1883 result->left.op = type;
1887 /* Create an AST node describing a reference type. */
1889 static const struct rust_op *
1890 ast_reference_type (const struct rust_op *type)
1892 struct rust_op *result = ast_basic_type (TYPE_CODE_REF);
1894 result->left.op = type;
1898 /* Create an AST node describing a pointer type. */
1900 static const struct rust_op *
1901 ast_pointer_type (const struct rust_op *type, int is_mut)
1903 struct rust_op *result = ast_basic_type (TYPE_CODE_PTR);
1905 result->left.op = type;
1906 /* For the time being we ignore is_mut. */
1910 /* Create an AST node describing a function type. */
1912 static const struct rust_op *
1913 ast_function_type (const struct rust_op *rtype, rust_op_vector *params)
1915 struct rust_op *result = ast_basic_type (TYPE_CODE_FUNC);
1917 result->left.op = rtype;
1918 result->right.params = params;
1922 /* Create an AST node describing a tuple type. */
1924 static const struct rust_op *
1925 ast_tuple_type (rust_op_vector *params)
1927 struct rust_op *result = ast_basic_type (TYPE_CODE_STRUCT);
1929 result->left.params = params;
1933 /* A helper to appropriately munge NAME and BLOCK depending on the
1934 presence of a leading "::". */
1937 munge_name_and_block (const char **name, const struct block **block)
1939 /* If it is a global reference, skip the current block in favor of
1940 the static block. */
1941 if (strncmp (*name, "::", 2) == 0)
1944 *block = block_static_block (*block);
1948 /* Like lookup_symbol, but handles Rust namespace conventions, and
1949 doesn't require field_of_this_result. */
1951 static struct block_symbol
1952 rust_lookup_symbol (const char *name, const struct block *block,
1953 const domain_enum domain)
1955 struct block_symbol result;
1957 munge_name_and_block (&name, &block);
1959 result = lookup_symbol (name, block, domain, NULL);
1960 if (result.symbol != NULL)
1961 update_innermost_block (result);
1965 /* Look up a type, following Rust namespace conventions. */
1967 static struct type *
1968 rust_lookup_type (const char *name, const struct block *block)
1970 struct block_symbol result;
1973 munge_name_and_block (&name, &block);
1975 result = lookup_symbol (name, block, STRUCT_DOMAIN, NULL);
1976 if (result.symbol != NULL)
1978 update_innermost_block (result);
1979 return SYMBOL_TYPE (result.symbol);
1982 type = lookup_typename (current_parser->language (), current_parser->arch (),
1987 /* Last chance, try a built-in type. */
1988 return language_lookup_primitive_type (current_parser->language (),
1989 current_parser->arch (),
1993 static struct type *convert_ast_to_type (struct parser_state *state,
1994 const struct rust_op *operation);
1995 static const char *convert_name (struct parser_state *state,
1996 const struct rust_op *operation);
1998 /* Convert a vector of rust_ops representing types to a vector of
2001 static std::vector<struct type *>
2002 convert_params_to_types (struct parser_state *state, rust_op_vector *params)
2004 std::vector<struct type *> result;
2006 for (const rust_op *op : *params)
2007 result.push_back (convert_ast_to_type (state, op));
2012 /* Convert a rust_op representing a type to a struct type *. */
2014 static struct type *
2015 convert_ast_to_type (struct parser_state *state,
2016 const struct rust_op *operation)
2018 struct type *type, *result = NULL;
2020 if (operation->opcode == OP_VAR_VALUE)
2022 const char *varname = convert_name (state, operation);
2024 result = rust_lookup_type (varname, expression_context_block);
2026 error (_("No typed name '%s' in current context"), varname);
2030 gdb_assert (operation->opcode == OP_TYPE);
2032 switch (operation->typecode)
2034 case TYPE_CODE_ARRAY:
2035 type = convert_ast_to_type (state, operation->left.op);
2036 if (operation->right.typed_val_int.val < 0)
2037 error (_("Negative array length"));
2038 result = lookup_array_range_type (type, 0,
2039 operation->right.typed_val_int.val - 1);
2042 case TYPE_CODE_COMPLEX:
2044 struct type *usize = rust_type ("usize");
2046 type = convert_ast_to_type (state, operation->left.op);
2047 result = rust_slice_type ("&[*gdb*]", type, usize);
2053 /* For now we treat &x and *x identically. */
2054 type = convert_ast_to_type (state, operation->left.op);
2055 result = lookup_pointer_type (type);
2058 case TYPE_CODE_FUNC:
2060 std::vector<struct type *> args
2061 (convert_params_to_types (state, operation->right.params));
2062 struct type **argtypes = NULL;
2064 type = convert_ast_to_type (state, operation->left.op);
2066 argtypes = args.data ();
2069 = lookup_function_type_with_arguments (type, args.size (),
2071 result = lookup_pointer_type (result);
2075 case TYPE_CODE_STRUCT:
2077 std::vector<struct type *> args
2078 (convert_params_to_types (state, operation->left.params));
2083 obstack_1grow (work_obstack, '(');
2084 for (i = 0; i < args.size (); ++i)
2086 std::string type_name = type_to_string (args[i]);
2089 obstack_1grow (work_obstack, ',');
2090 obstack_grow_str (work_obstack, type_name.c_str ());
2093 obstack_grow_str0 (work_obstack, ")");
2094 name = (const char *) obstack_finish (work_obstack);
2096 /* We don't allow creating new tuple types (yet), but we do
2097 allow looking up existing tuple types. */
2098 result = rust_lookup_type (name, expression_context_block);
2100 error (_("could not find tuple type '%s'"), name);
2105 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_type");
2108 gdb_assert (result != NULL);
2112 /* A helper function to turn a rust_op representing a name into a full
2113 name. This applies generic arguments as needed. The returned name
2114 is allocated on the work obstack. */
2117 convert_name (struct parser_state *state, const struct rust_op *operation)
2121 gdb_assert (operation->opcode == OP_VAR_VALUE);
2123 if (operation->right.params == NULL)
2124 return operation->left.sval.ptr;
2126 std::vector<struct type *> types
2127 (convert_params_to_types (state, operation->right.params));
2129 obstack_grow_str (work_obstack, operation->left.sval.ptr);
2130 obstack_1grow (work_obstack, '<');
2131 for (i = 0; i < types.size (); ++i)
2133 std::string type_name = type_to_string (types[i]);
2136 obstack_1grow (work_obstack, ',');
2138 obstack_grow_str (work_obstack, type_name.c_str ());
2140 obstack_grow_str0 (work_obstack, ">");
2142 return (const char *) obstack_finish (work_obstack);
2145 static void convert_ast_to_expression (struct parser_state *state,
2146 const struct rust_op *operation,
2147 const struct rust_op *top,
2148 bool want_type = false);
2150 /* A helper function that converts a vec of rust_ops to a gdb
2154 convert_params_to_expression (struct parser_state *state,
2155 rust_op_vector *params,
2156 const struct rust_op *top)
2158 for (const rust_op *elem : *params)
2159 convert_ast_to_expression (state, elem, top);
2162 /* Lower a rust_op to a gdb expression. STATE is the parser state.
2163 OPERATION is the operation to lower. TOP is a pointer to the
2164 top-most operation; it is used to handle the special case where the
2165 top-most expression is an identifier and can be optionally lowered
2166 to OP_TYPE. WANT_TYPE is a flag indicating that, if the expression
2167 is the name of a type, then emit an OP_TYPE for it (rather than
2168 erroring). If WANT_TYPE is set, then the similar TOP handling is
2172 convert_ast_to_expression (struct parser_state *state,
2173 const struct rust_op *operation,
2174 const struct rust_op *top,
2177 switch (operation->opcode)
2180 write_exp_elt_opcode (state, OP_LONG);
2181 write_exp_elt_type (state, operation->left.typed_val_int.type);
2182 write_exp_elt_longcst (state, operation->left.typed_val_int.val);
2183 write_exp_elt_opcode (state, OP_LONG);
2187 write_exp_elt_opcode (state, OP_DOUBLE);
2188 write_exp_elt_type (state, operation->left.typed_val_float.type);
2189 write_exp_elt_dblcst (state, operation->left.typed_val_float.dval);
2190 write_exp_elt_opcode (state, OP_DOUBLE);
2193 case STRUCTOP_STRUCT:
2195 convert_ast_to_expression (state, operation->left.op, top);
2197 if (operation->completing)
2198 mark_struct_expression (state);
2199 write_exp_elt_opcode (state, STRUCTOP_STRUCT);
2200 write_exp_string (state, operation->right.sval);
2201 write_exp_elt_opcode (state, STRUCTOP_STRUCT);
2205 case STRUCTOP_ANONYMOUS:
2207 convert_ast_to_expression (state, operation->left.op, top);
2209 write_exp_elt_opcode (state, STRUCTOP_ANONYMOUS);
2210 write_exp_elt_longcst (state, operation->right.typed_val_int.val);
2211 write_exp_elt_opcode (state, STRUCTOP_ANONYMOUS);
2216 convert_ast_to_expression (state, operation->left.op, top, true);
2217 write_exp_elt_opcode (state, UNOP_SIZEOF);
2222 case UNOP_COMPLEMENT:
2225 convert_ast_to_expression (state, operation->left.op, top);
2226 write_exp_elt_opcode (state, operation->opcode);
2229 case BINOP_SUBSCRIPT:
2236 case BINOP_BITWISE_AND:
2237 case BINOP_BITWISE_IOR:
2238 case BINOP_BITWISE_XOR:
2241 case BINOP_LOGICAL_OR:
2242 case BINOP_LOGICAL_AND:
2244 case BINOP_NOTEQUAL:
2251 convert_ast_to_expression (state, operation->left.op, top);
2252 convert_ast_to_expression (state, operation->right.op, top);
2253 if (operation->compound_assignment)
2255 write_exp_elt_opcode (state, BINOP_ASSIGN_MODIFY);
2256 write_exp_elt_opcode (state, operation->opcode);
2257 write_exp_elt_opcode (state, BINOP_ASSIGN_MODIFY);
2260 write_exp_elt_opcode (state, operation->opcode);
2262 if (operation->compound_assignment
2263 || operation->opcode == BINOP_ASSIGN)
2267 type = language_lookup_primitive_type (parse_language (state),
2268 parse_gdbarch (state),
2271 write_exp_elt_opcode (state, OP_LONG);
2272 write_exp_elt_type (state, type);
2273 write_exp_elt_longcst (state, 0);
2274 write_exp_elt_opcode (state, OP_LONG);
2276 write_exp_elt_opcode (state, BINOP_COMMA);
2282 struct type *type = convert_ast_to_type (state, operation->right.op);
2284 convert_ast_to_expression (state, operation->left.op, top);
2285 write_exp_elt_opcode (state, UNOP_CAST);
2286 write_exp_elt_type (state, type);
2287 write_exp_elt_opcode (state, UNOP_CAST);
2293 if (operation->left.op->opcode == OP_VAR_VALUE)
2296 const char *varname = convert_name (state, operation->left.op);
2298 type = rust_lookup_type (varname, expression_context_block);
2301 /* This is actually a tuple struct expression, not a
2303 rust_op_vector *params = operation->right.params;
2305 if (TYPE_CODE (type) != TYPE_CODE_NAMESPACE)
2307 if (!rust_tuple_struct_type_p (type))
2308 error (_("Type %s is not a tuple struct"), varname);
2310 for (int i = 0; i < params->size (); ++i)
2312 char *cell = get_print_cell ();
2314 xsnprintf (cell, PRINT_CELL_SIZE, "__%d", i);
2315 write_exp_elt_opcode (state, OP_NAME);
2316 write_exp_string (state, make_stoken (cell));
2317 write_exp_elt_opcode (state, OP_NAME);
2319 convert_ast_to_expression (state, (*params)[i], top);
2322 write_exp_elt_opcode (state, OP_AGGREGATE);
2323 write_exp_elt_type (state, type);
2324 write_exp_elt_longcst (state, 2 * params->size ());
2325 write_exp_elt_opcode (state, OP_AGGREGATE);
2330 convert_ast_to_expression (state, operation->left.op, top);
2331 convert_params_to_expression (state, operation->right.params, top);
2332 write_exp_elt_opcode (state, OP_FUNCALL);
2333 write_exp_elt_longcst (state, operation->right.params->size ());
2334 write_exp_elt_longcst (state, OP_FUNCALL);
2339 gdb_assert (operation->left.op == NULL);
2340 convert_params_to_expression (state, operation->right.params, top);
2341 write_exp_elt_opcode (state, OP_ARRAY);
2342 write_exp_elt_longcst (state, 0);
2343 write_exp_elt_longcst (state, operation->right.params->size () - 1);
2344 write_exp_elt_longcst (state, OP_ARRAY);
2349 struct block_symbol sym;
2350 const char *varname;
2352 if (operation->left.sval.ptr[0] == '$')
2354 write_dollar_variable (state, operation->left.sval);
2358 varname = convert_name (state, operation);
2359 sym = rust_lookup_symbol (varname, expression_context_block,
2361 if (sym.symbol != NULL && SYMBOL_CLASS (sym.symbol) != LOC_TYPEDEF)
2363 write_exp_elt_opcode (state, OP_VAR_VALUE);
2364 write_exp_elt_block (state, sym.block);
2365 write_exp_elt_sym (state, sym.symbol);
2366 write_exp_elt_opcode (state, OP_VAR_VALUE);
2370 struct type *type = NULL;
2372 if (sym.symbol != NULL)
2374 gdb_assert (SYMBOL_CLASS (sym.symbol) == LOC_TYPEDEF);
2375 type = SYMBOL_TYPE (sym.symbol);
2378 type = rust_lookup_type (varname, expression_context_block);
2380 error (_("No symbol '%s' in current context"), varname);
2383 && TYPE_CODE (type) == TYPE_CODE_STRUCT
2384 && TYPE_NFIELDS (type) == 0)
2386 /* A unit-like struct. */
2387 write_exp_elt_opcode (state, OP_AGGREGATE);
2388 write_exp_elt_type (state, type);
2389 write_exp_elt_longcst (state, 0);
2390 write_exp_elt_opcode (state, OP_AGGREGATE);
2392 else if (want_type || operation == top)
2394 write_exp_elt_opcode (state, OP_TYPE);
2395 write_exp_elt_type (state, type);
2396 write_exp_elt_opcode (state, OP_TYPE);
2399 error (_("Found type '%s', which can't be "
2400 "evaluated in this context"),
2410 rust_set_vector *fields = operation->right.field_inits;
2415 for (const set_field &init : *fields)
2417 if (init.name.ptr != NULL)
2419 write_exp_elt_opcode (state, OP_NAME);
2420 write_exp_string (state, init.name);
2421 write_exp_elt_opcode (state, OP_NAME);
2425 convert_ast_to_expression (state, init.init, top);
2428 if (init.name.ptr == NULL)
2430 /* This is handled differently from Ada in our
2432 write_exp_elt_opcode (state, OP_OTHERS);
2436 name = convert_name (state, operation->left.op);
2437 type = rust_lookup_type (name, expression_context_block);
2439 error (_("Could not find type '%s'"), operation->left.sval.ptr);
2441 if (TYPE_CODE (type) != TYPE_CODE_STRUCT
2442 || rust_tuple_type_p (type)
2443 || rust_tuple_struct_type_p (type))
2444 error (_("Struct expression applied to non-struct type"));
2446 write_exp_elt_opcode (state, OP_AGGREGATE);
2447 write_exp_elt_type (state, type);
2448 write_exp_elt_longcst (state, length);
2449 write_exp_elt_opcode (state, OP_AGGREGATE);
2455 write_exp_elt_opcode (state, OP_STRING);
2456 write_exp_string (state, operation->left.sval);
2457 write_exp_elt_opcode (state, OP_STRING);
2463 enum range_type kind = BOTH_BOUND_DEFAULT;
2465 if (operation->left.op != NULL)
2467 convert_ast_to_expression (state, operation->left.op, top);
2468 kind = HIGH_BOUND_DEFAULT;
2470 if (operation->right.op != NULL)
2472 convert_ast_to_expression (state, operation->right.op, top);
2473 if (kind == BOTH_BOUND_DEFAULT)
2474 kind = LOW_BOUND_DEFAULT;
2477 gdb_assert (kind == HIGH_BOUND_DEFAULT);
2478 kind = NONE_BOUND_DEFAULT;
2481 write_exp_elt_opcode (state, OP_RANGE);
2482 write_exp_elt_longcst (state, kind);
2483 write_exp_elt_opcode (state, OP_RANGE);
2488 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_expression");
2494 /* The parser as exposed to gdb. */
2497 rust_parse (struct parser_state *state)
2501 /* This sets various globals and also clears them on
2503 rust_parser parser (state);
2505 result = rustyyparse ();
2507 if (!result || (parse_completion && parser.rust_ast != NULL))
2508 convert_ast_to_expression (state, parser.rust_ast, parser.rust_ast);
2513 /* The parser error handler. */
2516 rustyyerror (const char *msg)
2518 const char *where = prev_lexptr ? prev_lexptr : lexptr;
2519 error (_("%s in expression, near `%s'."), (msg ? msg : "Error"), where);
2526 /* Initialize the lexer for testing. */
2529 rust_lex_test_init (const char *input)
2536 /* A test helper that lexes a string, expecting a single token. It
2537 returns the lexer data for this token. */
2540 rust_lex_test_one (const char *input, int expected)
2545 rust_lex_test_init (input);
2547 token = rustyylex ();
2548 SELF_CHECK (token == expected);
2549 result = rustyylval;
2553 token = rustyylex ();
2554 SELF_CHECK (token == 0);
2560 /* Test that INPUT lexes as the integer VALUE. */
2563 rust_lex_int_test (const char *input, int value, int kind)
2565 RUSTSTYPE result = rust_lex_test_one (input, kind);
2566 SELF_CHECK (result.typed_val_int.val == value);
2569 /* Test that INPUT throws an exception with text ERR. */
2572 rust_lex_exception_test (const char *input, const char *err)
2576 /* The "kind" doesn't matter. */
2577 rust_lex_test_one (input, DECIMAL_INTEGER);
2580 CATCH (except, RETURN_MASK_ERROR)
2582 SELF_CHECK (strcmp (except.message, err) == 0);
2587 /* Test that INPUT lexes as the identifier, string, or byte-string
2588 VALUE. KIND holds the expected token kind. */
2591 rust_lex_stringish_test (const char *input, const char *value, int kind)
2593 RUSTSTYPE result = rust_lex_test_one (input, kind);
2594 SELF_CHECK (result.sval.length == strlen (value));
2595 SELF_CHECK (strncmp (result.sval.ptr, value, result.sval.length) == 0);
2598 /* Helper to test that a string parses as a given token sequence. */
2601 rust_lex_test_sequence (const char *input, int len, const int expected[])
2608 for (i = 0; i < len; ++i)
2610 int token = rustyylex ();
2612 SELF_CHECK (token == expected[i]);
2616 /* Tests for an integer-parsing corner case. */
2619 rust_lex_test_trailing_dot (void)
2621 const int expected1[] = { DECIMAL_INTEGER, '.', IDENT, '(', ')', 0 };
2622 const int expected2[] = { INTEGER, '.', IDENT, '(', ')', 0 };
2623 const int expected3[] = { FLOAT, EQEQ, '(', ')', 0 };
2624 const int expected4[] = { DECIMAL_INTEGER, DOTDOT, DECIMAL_INTEGER, 0 };
2626 rust_lex_test_sequence ("23.g()", ARRAY_SIZE (expected1), expected1);
2627 rust_lex_test_sequence ("23_0.g()", ARRAY_SIZE (expected2), expected2);
2628 rust_lex_test_sequence ("23.==()", ARRAY_SIZE (expected3), expected3);
2629 rust_lex_test_sequence ("23..25", ARRAY_SIZE (expected4), expected4);
2632 /* Tests of completion. */
2635 rust_lex_test_completion (void)
2637 const int expected[] = { IDENT, '.', COMPLETE, 0 };
2639 parse_completion = 1;
2641 rust_lex_test_sequence ("something.wha", ARRAY_SIZE (expected), expected);
2642 rust_lex_test_sequence ("something.", ARRAY_SIZE (expected), expected);
2644 parse_completion = 0;
2647 /* Test pushback. */
2650 rust_lex_test_push_back (void)
2654 rust_lex_test_init (">>=");
2656 token = rustyylex ();
2657 SELF_CHECK (token == COMPOUND_ASSIGN);
2658 SELF_CHECK (rustyylval.opcode == BINOP_RSH);
2660 rust_push_back ('=');
2662 token = rustyylex ();
2663 SELF_CHECK (token == '=');
2665 token = rustyylex ();
2666 SELF_CHECK (token == 0);
2669 /* Unit test the lexer. */
2672 rust_lex_tests (void)
2676 auto_obstack test_obstack;
2677 scoped_restore obstack_holder = make_scoped_restore (&work_obstack,
2682 rust_lex_test_one ("", 0);
2683 rust_lex_test_one (" \t \n \r ", 0);
2684 rust_lex_test_one ("thread 23", 0);
2685 rust_lex_test_one ("task 23", 0);
2686 rust_lex_test_one ("th 104", 0);
2687 rust_lex_test_one ("ta 97", 0);
2689 rust_lex_int_test ("'z'", 'z', INTEGER);
2690 rust_lex_int_test ("'\\xff'", 0xff, INTEGER);
2691 rust_lex_int_test ("'\\u{1016f}'", 0x1016f, INTEGER);
2692 rust_lex_int_test ("b'z'", 'z', INTEGER);
2693 rust_lex_int_test ("b'\\xfe'", 0xfe, INTEGER);
2694 rust_lex_int_test ("b'\\xFE'", 0xfe, INTEGER);
2695 rust_lex_int_test ("b'\\xfE'", 0xfe, INTEGER);
2697 /* Test all escapes in both modes. */
2698 rust_lex_int_test ("'\\n'", '\n', INTEGER);
2699 rust_lex_int_test ("'\\r'", '\r', INTEGER);
2700 rust_lex_int_test ("'\\t'", '\t', INTEGER);
2701 rust_lex_int_test ("'\\\\'", '\\', INTEGER);
2702 rust_lex_int_test ("'\\0'", '\0', INTEGER);
2703 rust_lex_int_test ("'\\''", '\'', INTEGER);
2704 rust_lex_int_test ("'\\\"'", '"', INTEGER);
2706 rust_lex_int_test ("b'\\n'", '\n', INTEGER);
2707 rust_lex_int_test ("b'\\r'", '\r', INTEGER);
2708 rust_lex_int_test ("b'\\t'", '\t', INTEGER);
2709 rust_lex_int_test ("b'\\\\'", '\\', INTEGER);
2710 rust_lex_int_test ("b'\\0'", '\0', INTEGER);
2711 rust_lex_int_test ("b'\\''", '\'', INTEGER);
2712 rust_lex_int_test ("b'\\\"'", '"', INTEGER);
2714 rust_lex_exception_test ("'z", "Unterminated character literal");
2715 rust_lex_exception_test ("b'\\x0'", "Not enough hex digits seen");
2716 rust_lex_exception_test ("b'\\u{0}'", "Unicode escape in byte literal");
2717 rust_lex_exception_test ("'\\x0'", "Not enough hex digits seen");
2718 rust_lex_exception_test ("'\\u0'", "Missing '{' in Unicode escape");
2719 rust_lex_exception_test ("'\\u{0", "Missing '}' in Unicode escape");
2720 rust_lex_exception_test ("'\\u{0000007}", "Overlong hex escape");
2721 rust_lex_exception_test ("'\\u{}", "Not enough hex digits seen");
2722 rust_lex_exception_test ("'\\Q'", "Invalid escape \\Q in literal");
2723 rust_lex_exception_test ("b'\\Q'", "Invalid escape \\Q in literal");
2725 rust_lex_int_test ("23", 23, DECIMAL_INTEGER);
2726 rust_lex_int_test ("2_344__29", 234429, INTEGER);
2727 rust_lex_int_test ("0x1f", 0x1f, INTEGER);
2728 rust_lex_int_test ("23usize", 23, INTEGER);
2729 rust_lex_int_test ("23i32", 23, INTEGER);
2730 rust_lex_int_test ("0x1_f", 0x1f, INTEGER);
2731 rust_lex_int_test ("0b1_101011__", 0x6b, INTEGER);
2732 rust_lex_int_test ("0o001177i64", 639, INTEGER);
2734 rust_lex_test_trailing_dot ();
2736 rust_lex_test_one ("23.", FLOAT);
2737 rust_lex_test_one ("23.99f32", FLOAT);
2738 rust_lex_test_one ("23e7", FLOAT);
2739 rust_lex_test_one ("23E-7", FLOAT);
2740 rust_lex_test_one ("23e+7", FLOAT);
2741 rust_lex_test_one ("23.99e+7f64", FLOAT);
2742 rust_lex_test_one ("23.82f32", FLOAT);
2744 rust_lex_stringish_test ("hibob", "hibob", IDENT);
2745 rust_lex_stringish_test ("hibob__93", "hibob__93", IDENT);
2746 rust_lex_stringish_test ("thread", "thread", IDENT);
2748 rust_lex_stringish_test ("\"string\"", "string", STRING);
2749 rust_lex_stringish_test ("\"str\\ting\"", "str\ting", STRING);
2750 rust_lex_stringish_test ("\"str\\\"ing\"", "str\"ing", STRING);
2751 rust_lex_stringish_test ("r\"str\\ing\"", "str\\ing", STRING);
2752 rust_lex_stringish_test ("r#\"str\\ting\"#", "str\\ting", STRING);
2753 rust_lex_stringish_test ("r###\"str\\\"ing\"###", "str\\\"ing", STRING);
2755 rust_lex_stringish_test ("b\"string\"", "string", BYTESTRING);
2756 rust_lex_stringish_test ("b\"\x73tring\"", "string", BYTESTRING);
2757 rust_lex_stringish_test ("b\"str\\\"ing\"", "str\"ing", BYTESTRING);
2758 rust_lex_stringish_test ("br####\"\\x73tring\"####", "\\x73tring",
2761 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
2762 rust_lex_test_one (identifier_tokens[i].name, identifier_tokens[i].value);
2764 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
2765 rust_lex_test_one (operator_tokens[i].name, operator_tokens[i].value);
2767 rust_lex_test_completion ();
2768 rust_lex_test_push_back ();
2773 #endif /* GDB_SELF_TEST */
2776 _initialize_rust_exp (void)
2778 int code = regcomp (&number_regex, number_regex_text, REG_EXTENDED);
2779 /* If the regular expression was incorrect, it was a programming
2781 gdb_assert (code == 0);
2784 register_self_test (rust_lex_tests);