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
43 typedef std::vector<const struct rust_op *> rust_op_vector;
45 /* A typed integer constant. */
53 /* A typed floating point constant. */
55 struct typed_val_float
61 /* An identifier and an expression. This is used to represent one
62 element of a struct initializer. */
67 const struct rust_op *init;
70 typedef std::vector<set_field> rust_set_vector;
72 static int rustyylex (void);
73 static void rust_push_back (char c);
74 static const char *rust_copy_name (const char *, int);
75 static struct stoken rust_concat3 (const char *, const char *, const char *);
76 static struct stoken make_stoken (const char *);
77 static struct block_symbol rust_lookup_symbol (const char *name,
78 const struct block *block,
79 const domain_enum domain);
80 static struct type *rust_lookup_type (const char *name,
81 const struct block *block);
82 static struct type *rust_type (const char *name);
84 static const struct rust_op *crate_name (const struct rust_op *name);
85 static const struct rust_op *super_name (const struct rust_op *name,
86 unsigned int n_supers);
88 static const struct rust_op *ast_operation (enum exp_opcode opcode,
89 const struct rust_op *left,
90 const struct rust_op *right);
91 static const struct rust_op *ast_compound_assignment
92 (enum exp_opcode opcode, const struct rust_op *left,
93 const struct rust_op *rust_op);
94 static const struct rust_op *ast_literal (struct typed_val_int val);
95 static const struct rust_op *ast_dliteral (struct typed_val_float val);
96 static const struct rust_op *ast_structop (const struct rust_op *left,
99 static const struct rust_op *ast_structop_anonymous
100 (const struct rust_op *left, struct typed_val_int number);
101 static const struct rust_op *ast_unary (enum exp_opcode opcode,
102 const struct rust_op *expr);
103 static const struct rust_op *ast_cast (const struct rust_op *expr,
104 const struct rust_op *type);
105 static const struct rust_op *ast_call_ish (enum exp_opcode opcode,
106 const struct rust_op *expr,
107 rust_op_vector *params);
108 static const struct rust_op *ast_path (struct stoken name,
109 rust_op_vector *params);
110 static const struct rust_op *ast_string (struct stoken str);
111 static const struct rust_op *ast_struct (const struct rust_op *name,
112 rust_set_vector *fields);
113 static const struct rust_op *ast_range (const struct rust_op *lhs,
114 const struct rust_op *rhs);
115 static const struct rust_op *ast_array_type (const struct rust_op *lhs,
116 struct typed_val_int val);
117 static const struct rust_op *ast_slice_type (const struct rust_op *type);
118 static const struct rust_op *ast_reference_type (const struct rust_op *type);
119 static const struct rust_op *ast_pointer_type (const struct rust_op *type,
121 static const struct rust_op *ast_function_type (const struct rust_op *result,
122 rust_op_vector *params);
123 static const struct rust_op *ast_tuple_type (rust_op_vector *params);
125 /* The current rust parser. */
128 static rust_parser *current_parser;
130 /* A regular expression for matching Rust numbers. This is split up
131 since it is very long and this gives us a way to comment the
134 static const char *number_regex_text =
135 /* subexpression 1: allows use of alternation, otherwise uninteresting */
137 /* First comes floating point. */
138 /* Recognize number after the decimal point, with optional
139 exponent and optional type suffix.
140 subexpression 2: allows "?", otherwise uninteresting
141 subexpression 3: if present, type suffix
143 "[0-9][0-9_]*\\.[0-9][0-9_]*([eE][-+]?[0-9][0-9_]*)?(f32|f64)?"
144 #define FLOAT_TYPE1 3
146 /* Recognize exponent without decimal point, with optional type
148 subexpression 4: if present, type suffix
150 #define FLOAT_TYPE2 4
151 "[0-9][0-9_]*[eE][-+]?[0-9][0-9_]*(f32|f64)?"
153 /* "23." is a valid floating point number, but "23.e5" and
154 "23.f32" are not. So, handle the trailing-. case
158 /* Finally come integers.
159 subexpression 5: text of integer
160 subexpression 6: if present, type suffix
161 subexpression 7: allows use of alternation, otherwise uninteresting
165 "(0x[a-fA-F0-9_]+|0o[0-7_]+|0b[01_]+|[0-9][0-9_]*)"
166 "([iu](size|8|16|32|64))?"
168 /* The number of subexpressions to allocate space for, including the
169 "0th" whole match subexpression. */
170 #define NUM_SUBEXPRESSIONS 8
172 /* The compiled number-matching regex. */
174 static regex_t number_regex;
176 /* Obstack for data temporarily allocated during parsing. Points to
177 the obstack in the rust_parser, or to a temporary obstack during
180 static auto_obstack *work_obstack;
182 /* An instance of this is created before parsing, and destroyed when
183 parsing is finished. */
187 rust_parser (struct parser_state *state)
188 : rust_ast (nullptr),
191 gdb_assert (current_parser == nullptr);
192 current_parser = this;
193 work_obstack = &obstack;
198 /* Clean up the globals we set. */
199 current_parser = nullptr;
200 work_obstack = nullptr;
203 /* Create a new rust_set_vector. The storage for the new vector is
204 managed by this class. */
205 rust_set_vector *new_set_vector ()
207 rust_set_vector *result = new rust_set_vector;
208 set_vectors.push_back (std::unique_ptr<rust_set_vector> (result));
212 /* Create a new rust_ops_vector. The storage for the new vector is
213 managed by this class. */
214 rust_op_vector *new_op_vector ()
216 rust_op_vector *result = new rust_op_vector;
217 op_vectors.push_back (std::unique_ptr<rust_op_vector> (result));
221 /* Return the parser's language. */
222 const struct language_defn *language () const
224 return parse_language (pstate);
227 /* Return the parser's gdbarch. */
228 struct gdbarch *arch () const
230 return parse_gdbarch (pstate);
233 /* A pointer to this is installed globally. */
234 auto_obstack obstack;
236 /* Result of parsing. Points into obstack. */
237 const struct rust_op *rust_ast;
239 /* This keeps track of the various vectors we allocate. */
240 std::vector<std::unique_ptr<rust_set_vector>> set_vectors;
241 std::vector<std::unique_ptr<rust_op_vector>> op_vectors;
243 /* The parser state gdb gave us. */
244 struct parser_state *pstate;
251 /* A typed integer constant. */
252 struct typed_val_int typed_val_int;
254 /* A typed floating point constant. */
255 struct typed_val_float typed_val_float;
257 /* An identifier or string. */
260 /* A token representing an opcode, like "==". */
261 enum exp_opcode opcode;
263 /* A list of expressions; for example, the arguments to a function
265 rust_op_vector *params;
267 /* A list of field initializers. */
268 rust_set_vector *field_inits;
270 /* A single field initializer. */
271 struct set_field one_field_init;
274 const struct rust_op *op;
276 /* A plain integer, for example used to count the number of
277 "super::" prefixes on a path. */
283 /* Rust AST operations. We build a tree of these; then lower them
284 to gdb expressions when parsing has completed. */
289 enum exp_opcode opcode;
290 /* If OPCODE is OP_TYPE, then this holds information about what type
291 is described by this node. */
292 enum type_code typecode;
293 /* Indicates whether OPCODE actually represents a compound
294 assignment. For example, if OPCODE is GTGT and this is false,
295 then this rust_op represents an ordinary ">>"; but if this is
296 true, then this rust_op represents ">>=". Unused in other
298 unsigned int compound_assignment : 1;
299 /* Only used by a field expression; if set, indicates that the field
300 name occurred at the end of the expression and is eligible for
302 unsigned int completing : 1;
303 /* Operands of expression. Which one is used and how depends on the
304 particular opcode. */
313 %token <sval> COMPLETE
314 %token <typed_val_int> INTEGER
315 %token <typed_val_int> DECIMAL_INTEGER
317 %token <sval> BYTESTRING
318 %token <typed_val_float> FLOAT
319 %token <opcode> COMPOUND_ASSIGN
321 /* Keyword tokens. */
322 %token <voidval> KW_AS
323 %token <voidval> KW_IF
324 %token <voidval> KW_TRUE
325 %token <voidval> KW_FALSE
326 %token <voidval> KW_SUPER
327 %token <voidval> KW_SELF
328 %token <voidval> KW_MUT
329 %token <voidval> KW_EXTERN
330 %token <voidval> KW_CONST
331 %token <voidval> KW_FN
332 %token <voidval> KW_SIZEOF
334 /* Operator tokens. */
335 %token <voidval> DOTDOT
336 %token <voidval> OROR
337 %token <voidval> ANDAND
338 %token <voidval> EQEQ
339 %token <voidval> NOTEQ
340 %token <voidval> LTEQ
341 %token <voidval> GTEQ
342 %token <voidval> LSH RSH
343 %token <voidval> COLONCOLON
344 %token <voidval> ARROW
347 %type <op> path_for_expr
348 %type <op> identifier_path_for_expr
349 %type <op> path_for_type
350 %type <op> identifier_path_for_type
351 %type <op> just_identifiers_for_type
353 %type <params> maybe_type_list
354 %type <params> type_list
356 %type <depth> super_path
360 %type <op> field_expr
363 %type <op> binop_expr
364 %type <op> binop_expr_expr
365 %type <op> type_cast_expr
366 %type <op> assignment_expr
367 %type <op> compound_assignment_expr
368 %type <op> paren_expr
371 %type <op> tuple_expr
373 %type <op> struct_expr
374 %type <op> array_expr
375 %type <op> range_expr
377 %type <params> expr_list
378 %type <params> maybe_expr_list
379 %type <params> paren_expr_list
381 %type <field_inits> struct_expr_list
382 %type <one_field_init> struct_expr_tail
386 %right '=' COMPOUND_ASSIGN
389 %nonassoc EQEQ NOTEQ '<' '>' LTEQ GTEQ
397 /* These could be %precedence in Bison, but that isn't a yacc
408 /* If we are completing and see a valid parse,
409 rust_ast will already have been set. */
410 if (current_parser->rust_ast == NULL)
411 current_parser->rust_ast = $1;
415 /* Note that the Rust grammar includes a method_call_expr, but we
416 handle this differently, to avoid a shift/reduce conflict with
428 | unop_expr /* Must precede call_expr because of ambiguity with sizeof. */
435 '(' expr ',' maybe_expr_list ')'
438 error (_("Tuple expressions not supported yet"));
445 struct typed_val_int val;
448 = language_lookup_primitive_type (current_parser->language (),
449 current_parser->arch (),
452 $$ = ast_literal (val);
456 /* To avoid a shift/reduce conflict with call_expr, we don't handle
457 tuple struct expressions here, but instead when examining the
460 path_for_expr '{' struct_expr_list '}'
461 { $$ = ast_struct ($1, $3); }
488 $$ = current_parser->new_set_vector ();
492 rust_set_vector *result = current_parser->new_set_vector ();
493 result->push_back ($1);
496 | IDENT ':' expr ',' struct_expr_list
508 '[' KW_MUT expr_list ']'
509 { $$ = ast_call_ish (OP_ARRAY, NULL, $3); }
511 { $$ = ast_call_ish (OP_ARRAY, NULL, $2); }
512 | '[' KW_MUT expr ';' expr ']'
513 { $$ = ast_operation (OP_RUST_ARRAY, $3, $5); }
514 | '[' expr ';' expr ']'
515 { $$ = ast_operation (OP_RUST_ARRAY, $2, $4); }
520 { $$ = ast_range ($1, NULL); }
522 { $$ = ast_range ($1, $3); }
524 { $$ = ast_range (NULL, $2); }
526 { $$ = ast_range (NULL, NULL); }
531 { $$ = ast_literal ($1); }
533 { $$ = ast_literal ($1); }
535 { $$ = ast_dliteral ($1); }
538 const struct rust_op *str = ast_string ($1);
539 struct set_field field;
540 struct typed_val_int val;
543 rust_set_vector *fields = current_parser->new_set_vector ();
545 /* Wrap the raw string in the &str struct. */
546 field.name.ptr = "data_ptr";
547 field.name.length = strlen (field.name.ptr);
548 field.init = ast_unary (UNOP_ADDR, ast_string ($1));
549 fields->push_back (field);
551 val.type = rust_type ("usize");
554 field.name.ptr = "length";
555 field.name.length = strlen (field.name.ptr);
556 field.init = ast_literal (val);
557 fields->push_back (field);
560 token.length = strlen (token.ptr);
561 $$ = ast_struct (ast_path (token, NULL), fields);
564 { $$ = ast_string ($1); }
567 struct typed_val_int val;
569 val.type = language_bool_type (current_parser->language (),
570 current_parser->arch ());
572 $$ = ast_literal (val);
576 struct typed_val_int val;
578 val.type = language_bool_type (current_parser->language (),
579 current_parser->arch ());
581 $$ = ast_literal (val);
587 { $$ = ast_structop ($1, $3.ptr, 0); }
590 $$ = ast_structop ($1, $3.ptr, 1);
591 current_parser->rust_ast = $$;
593 | expr '.' DECIMAL_INTEGER
594 { $$ = ast_structop_anonymous ($1, $3); }
599 { $$ = ast_operation (BINOP_SUBSCRIPT, $1, $3); }
604 { $$ = ast_unary (UNOP_PLUS, $2); }
606 | '-' expr %prec UNARY
607 { $$ = ast_unary (UNOP_NEG, $2); }
609 | '!' expr %prec UNARY
611 /* Note that we provide a Rust-specific evaluator
612 override for UNOP_COMPLEMENT, so it can do the
613 right thing for both bool and integral
615 $$ = ast_unary (UNOP_COMPLEMENT, $2);
618 | '*' expr %prec UNARY
619 { $$ = ast_unary (UNOP_IND, $2); }
621 | '&' expr %prec UNARY
622 { $$ = ast_unary (UNOP_ADDR, $2); }
624 | '&' KW_MUT expr %prec UNARY
625 { $$ = ast_unary (UNOP_ADDR, $3); }
626 | KW_SIZEOF '(' expr ')' %prec UNARY
627 { $$ = ast_unary (UNOP_SIZEOF, $3); }
634 | compound_assignment_expr
639 { $$ = ast_operation (BINOP_MUL, $1, $3); }
642 { $$ = ast_operation (BINOP_REPEAT, $1, $3); }
645 { $$ = ast_operation (BINOP_DIV, $1, $3); }
648 { $$ = ast_operation (BINOP_REM, $1, $3); }
651 { $$ = ast_operation (BINOP_LESS, $1, $3); }
654 { $$ = ast_operation (BINOP_GTR, $1, $3); }
657 { $$ = ast_operation (BINOP_BITWISE_AND, $1, $3); }
660 { $$ = ast_operation (BINOP_BITWISE_IOR, $1, $3); }
663 { $$ = ast_operation (BINOP_BITWISE_XOR, $1, $3); }
666 { $$ = ast_operation (BINOP_ADD, $1, $3); }
669 { $$ = ast_operation (BINOP_SUB, $1, $3); }
672 { $$ = ast_operation (BINOP_LOGICAL_OR, $1, $3); }
675 { $$ = ast_operation (BINOP_LOGICAL_AND, $1, $3); }
678 { $$ = ast_operation (BINOP_EQUAL, $1, $3); }
681 { $$ = ast_operation (BINOP_NOTEQUAL, $1, $3); }
684 { $$ = ast_operation (BINOP_LEQ, $1, $3); }
687 { $$ = ast_operation (BINOP_GEQ, $1, $3); }
690 { $$ = ast_operation (BINOP_LSH, $1, $3); }
693 { $$ = ast_operation (BINOP_RSH, $1, $3); }
698 { $$ = ast_cast ($1, $3); }
703 { $$ = ast_operation (BINOP_ASSIGN, $1, $3); }
706 compound_assignment_expr:
707 expr COMPOUND_ASSIGN expr
708 { $$ = ast_compound_assignment ($2, $1, $3); }
720 $$ = current_parser->new_op_vector ();
733 /* The result can't be NULL. */
734 $$ = current_parser->new_op_vector ();
749 { $$ = ast_call_ish (OP_FUNCALL, $1, $2); }
760 | super_path KW_SUPER COLONCOLON
768 { $$ = ast_path ($1, NULL); }
770 { $$ = ast_path (make_stoken ("self"), NULL); }
774 identifier_path_for_expr
775 | KW_SELF COLONCOLON identifier_path_for_expr
776 { $$ = super_name ($3, 0); }
777 | maybe_self_path super_path identifier_path_for_expr
778 { $$ = super_name ($3, $2); }
779 | COLONCOLON identifier_path_for_expr
780 { $$ = crate_name ($2); }
781 | KW_EXTERN identifier_path_for_expr
783 /* This is a gdb extension to make it possible to
784 refer to items in other crates. It just bypasses
785 adding the current crate to the front of the
787 $$ = ast_path (rust_concat3 ("::", $2->left.sval.ptr, NULL),
792 identifier_path_for_expr:
794 { $$ = ast_path ($1, NULL); }
795 | identifier_path_for_expr COLONCOLON IDENT
797 $$ = ast_path (rust_concat3 ($1->left.sval.ptr, "::",
801 | identifier_path_for_expr COLONCOLON '<' type_list '>'
802 { $$ = ast_path ($1->left.sval, $4); }
803 | identifier_path_for_expr COLONCOLON '<' type_list RSH
805 $$ = ast_path ($1->left.sval, $4);
806 rust_push_back ('>');
811 identifier_path_for_type
812 | KW_SELF COLONCOLON identifier_path_for_type
813 { $$ = super_name ($3, 0); }
814 | maybe_self_path super_path identifier_path_for_type
815 { $$ = super_name ($3, $2); }
816 | COLONCOLON identifier_path_for_type
817 { $$ = crate_name ($2); }
818 | KW_EXTERN identifier_path_for_type
820 /* This is a gdb extension to make it possible to
821 refer to items in other crates. It just bypasses
822 adding the current crate to the front of the
824 $$ = ast_path (rust_concat3 ("::", $2->left.sval.ptr, NULL),
829 just_identifiers_for_type:
831 { $$ = ast_path ($1, NULL); }
832 | just_identifiers_for_type COLONCOLON IDENT
834 $$ = ast_path (rust_concat3 ($1->left.sval.ptr, "::",
840 identifier_path_for_type:
841 just_identifiers_for_type
842 | just_identifiers_for_type '<' type_list '>'
843 { $$ = ast_path ($1->left.sval, $3); }
844 | just_identifiers_for_type '<' type_list RSH
846 $$ = ast_path ($1->left.sval, $3);
847 rust_push_back ('>');
853 | '[' type ';' INTEGER ']'
854 { $$ = ast_array_type ($2, $4); }
855 | '[' type ';' DECIMAL_INTEGER ']'
856 { $$ = ast_array_type ($2, $4); }
858 { $$ = ast_slice_type ($3); }
860 { $$ = ast_reference_type ($2); }
862 { $$ = ast_pointer_type ($3, 1); }
864 { $$ = ast_pointer_type ($3, 0); }
865 | KW_FN '(' maybe_type_list ')' ARROW type
866 { $$ = ast_function_type ($6, $3); }
867 | '(' maybe_type_list ')'
868 { $$ = ast_tuple_type ($2); }
881 rust_op_vector *result = current_parser->new_op_vector ();
882 result->push_back ($1);
894 /* A struct of this type is used to describe a token. */
900 enum exp_opcode opcode;
903 /* Identifier tokens. */
905 static const struct token_info identifier_tokens[] =
907 { "as", KW_AS, OP_NULL },
908 { "false", KW_FALSE, OP_NULL },
909 { "if", 0, OP_NULL },
910 { "mut", KW_MUT, OP_NULL },
911 { "const", KW_CONST, OP_NULL },
912 { "self", KW_SELF, OP_NULL },
913 { "super", KW_SUPER, OP_NULL },
914 { "true", KW_TRUE, OP_NULL },
915 { "extern", KW_EXTERN, OP_NULL },
916 { "fn", KW_FN, OP_NULL },
917 { "sizeof", KW_SIZEOF, OP_NULL },
920 /* Operator tokens, sorted longest first. */
922 static const struct token_info operator_tokens[] =
924 { ">>=", COMPOUND_ASSIGN, BINOP_RSH },
925 { "<<=", COMPOUND_ASSIGN, BINOP_LSH },
927 { "<<", LSH, OP_NULL },
928 { ">>", RSH, OP_NULL },
929 { "&&", ANDAND, OP_NULL },
930 { "||", OROR, OP_NULL },
931 { "==", EQEQ, OP_NULL },
932 { "!=", NOTEQ, OP_NULL },
933 { "<=", LTEQ, OP_NULL },
934 { ">=", GTEQ, OP_NULL },
935 { "+=", COMPOUND_ASSIGN, BINOP_ADD },
936 { "-=", COMPOUND_ASSIGN, BINOP_SUB },
937 { "*=", COMPOUND_ASSIGN, BINOP_MUL },
938 { "/=", COMPOUND_ASSIGN, BINOP_DIV },
939 { "%=", COMPOUND_ASSIGN, BINOP_REM },
940 { "&=", COMPOUND_ASSIGN, BINOP_BITWISE_AND },
941 { "|=", COMPOUND_ASSIGN, BINOP_BITWISE_IOR },
942 { "^=", COMPOUND_ASSIGN, BINOP_BITWISE_XOR },
944 { "::", COLONCOLON, OP_NULL },
945 { "..", DOTDOT, OP_NULL },
946 { "->", ARROW, OP_NULL }
949 /* Helper function to copy to the name obstack. */
952 rust_copy_name (const char *name, int len)
954 return (const char *) obstack_copy0 (work_obstack, name, len);
957 /* Helper function to make an stoken from a C string. */
960 make_stoken (const char *p)
962 struct stoken result;
965 result.length = strlen (result.ptr);
969 /* Helper function to concatenate three strings on the name
973 rust_concat3 (const char *s1, const char *s2, const char *s3)
975 return make_stoken (obconcat (work_obstack, s1, s2, s3, (char *) NULL));
978 /* Return an AST node referring to NAME, but relative to the crate's
981 static const struct rust_op *
982 crate_name (const struct rust_op *name)
984 std::string crate = rust_crate_for_block (expression_context_block);
985 struct stoken result;
987 gdb_assert (name->opcode == OP_VAR_VALUE);
990 error (_("Could not find crate for current location"));
991 result = make_stoken (obconcat (work_obstack, "::", crate.c_str (), "::",
992 name->left.sval.ptr, (char *) NULL));
994 return ast_path (result, name->right.params);
997 /* Create an AST node referring to a "super::" qualified name. IDENT
998 is the base name and N_SUPERS is how many "super::"s were
999 provided. N_SUPERS can be zero. */
1001 static const struct rust_op *
1002 super_name (const struct rust_op *ident, unsigned int n_supers)
1004 const char *scope = block_scope (expression_context_block);
1007 gdb_assert (ident->opcode == OP_VAR_VALUE);
1009 if (scope[0] == '\0')
1010 error (_("Couldn't find namespace scope for self::"));
1016 std::vector<int> offsets;
1017 unsigned int current_len;
1019 current_len = cp_find_first_component (scope);
1020 while (scope[current_len] != '\0')
1022 offsets.push_back (current_len);
1023 gdb_assert (scope[current_len] == ':');
1026 current_len += cp_find_first_component (scope
1030 len = offsets.size ();
1031 if (n_supers >= len)
1032 error (_("Too many super:: uses from '%s'"), scope);
1034 offset = offsets[len - n_supers];
1037 offset = strlen (scope);
1039 obstack_grow (work_obstack, "::", 2);
1040 obstack_grow (work_obstack, scope, offset);
1041 obstack_grow (work_obstack, "::", 2);
1042 obstack_grow0 (work_obstack, ident->left.sval.ptr, ident->left.sval.length);
1044 return ast_path (make_stoken ((const char *) obstack_finish (work_obstack)),
1045 ident->right.params);
1048 /* A helper that updates innermost_block as appropriate. */
1051 update_innermost_block (struct block_symbol sym)
1053 if (symbol_read_needs_frame (sym.symbol)
1054 && (innermost_block == NULL
1055 || contained_in (sym.block, innermost_block)))
1056 innermost_block = sym.block;
1059 /* A helper to look up a Rust type, or fail. This only works for
1060 types defined by rust_language_arch_info. */
1062 static struct type *
1063 rust_type (const char *name)
1067 type = language_lookup_primitive_type (current_parser->language (),
1068 current_parser->arch (),
1071 error (_("Could not find Rust type %s"), name);
1075 /* Lex a hex number with at least MIN digits and at most MAX
1079 lex_hex (int min, int max)
1081 uint32_t result = 0;
1083 /* We only want to stop at MAX if we're lexing a byte escape. */
1084 int check_max = min == max;
1086 while ((check_max ? len <= max : 1)
1087 && ((lexptr[0] >= 'a' && lexptr[0] <= 'f')
1088 || (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1089 || (lexptr[0] >= '0' && lexptr[0] <= '9')))
1092 if (lexptr[0] >= 'a' && lexptr[0] <= 'f')
1093 result = result + 10 + lexptr[0] - 'a';
1094 else if (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1095 result = result + 10 + lexptr[0] - 'A';
1097 result = result + lexptr[0] - '0';
1103 error (_("Not enough hex digits seen"));
1106 gdb_assert (min != max);
1107 error (_("Overlong hex escape"));
1113 /* Lex an escape. IS_BYTE is true if we're lexing a byte escape;
1114 otherwise we're lexing a character escape. */
1117 lex_escape (int is_byte)
1121 gdb_assert (lexptr[0] == '\\');
1127 result = lex_hex (2, 2);
1132 error (_("Unicode escape in byte literal"));
1134 if (lexptr[0] != '{')
1135 error (_("Missing '{' in Unicode escape"));
1137 result = lex_hex (1, 6);
1138 /* Could do range checks here. */
1139 if (lexptr[0] != '}')
1140 error (_("Missing '}' in Unicode escape"));
1174 error (_("Invalid escape \\%c in literal"), lexptr[0]);
1180 /* Lex a character constant. */
1183 lex_character (void)
1188 if (lexptr[0] == 'b')
1193 gdb_assert (lexptr[0] == '\'');
1195 /* This should handle UTF-8 here. */
1196 if (lexptr[0] == '\\')
1197 value = lex_escape (is_byte);
1200 value = lexptr[0] & 0xff;
1204 if (lexptr[0] != '\'')
1205 error (_("Unterminated character literal"));
1208 rustyylval.typed_val_int.val = value;
1209 rustyylval.typed_val_int.type = rust_type (is_byte ? "u8" : "char");
1214 /* Return the offset of the double quote if STR looks like the start
1215 of a raw string, or 0 if STR does not start a raw string. */
1218 starts_raw_string (const char *str)
1220 const char *save = str;
1225 while (str[0] == '#')
1232 /* Return true if STR looks like the end of a raw string that had N
1233 hashes at the start. */
1236 ends_raw_string (const char *str, int n)
1240 gdb_assert (str[0] == '"');
1241 for (i = 0; i < n; ++i)
1242 if (str[i + 1] != '#')
1247 /* Lex a string constant. */
1252 int is_byte = lexptr[0] == 'b';
1254 int len_in_chars = 0;
1258 raw_length = starts_raw_string (lexptr);
1259 lexptr += raw_length;
1260 gdb_assert (lexptr[0] == '"');
1269 if (lexptr[0] == '"' && ends_raw_string (lexptr, raw_length - 1))
1271 /* Exit with lexptr pointing after the final "#". */
1272 lexptr += raw_length;
1275 else if (lexptr[0] == '\0')
1276 error (_("Unexpected EOF in string"));
1278 value = lexptr[0] & 0xff;
1279 if (is_byte && value > 127)
1280 error (_("Non-ASCII value in raw byte string"));
1281 obstack_1grow (work_obstack, value);
1285 else if (lexptr[0] == '"')
1287 /* Make sure to skip the quote. */
1291 else if (lexptr[0] == '\\')
1293 value = lex_escape (is_byte);
1296 obstack_1grow (work_obstack, value);
1298 convert_between_encodings ("UTF-32", "UTF-8", (gdb_byte *) &value,
1299 sizeof (value), sizeof (value),
1300 work_obstack, translit_none);
1302 else if (lexptr[0] == '\0')
1303 error (_("Unexpected EOF in string"));
1306 value = lexptr[0] & 0xff;
1307 if (is_byte && value > 127)
1308 error (_("Non-ASCII value in byte string"));
1309 obstack_1grow (work_obstack, value);
1314 rustyylval.sval.length = obstack_object_size (work_obstack);
1315 rustyylval.sval.ptr = (const char *) obstack_finish (work_obstack);
1316 return is_byte ? BYTESTRING : STRING;
1319 /* Return true if STRING starts with whitespace followed by a digit. */
1322 space_then_number (const char *string)
1324 const char *p = string;
1326 while (p[0] == ' ' || p[0] == '\t')
1331 return *p >= '0' && *p <= '9';
1334 /* Return true if C can start an identifier. */
1337 rust_identifier_start_p (char c)
1339 return ((c >= 'a' && c <= 'z')
1340 || (c >= 'A' && c <= 'Z')
1345 /* Lex an identifier. */
1348 lex_identifier (void)
1350 const char *start = lexptr;
1351 unsigned int length;
1352 const struct token_info *token;
1354 int is_gdb_var = lexptr[0] == '$';
1356 gdb_assert (rust_identifier_start_p (lexptr[0]));
1360 /* For the time being this doesn't handle Unicode rules. Non-ASCII
1361 identifiers are gated anyway. */
1362 while ((lexptr[0] >= 'a' && lexptr[0] <= 'z')
1363 || (lexptr[0] >= 'A' && lexptr[0] <= 'Z')
1365 || (is_gdb_var && lexptr[0] == '$')
1366 || (lexptr[0] >= '0' && lexptr[0] <= '9'))
1370 length = lexptr - start;
1372 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
1374 if (length == strlen (identifier_tokens[i].name)
1375 && strncmp (identifier_tokens[i].name, start, length) == 0)
1377 token = &identifier_tokens[i];
1384 if (token->value == 0)
1386 /* Leave the terminating token alone. */
1391 else if (token == NULL
1392 && (strncmp (start, "thread", length) == 0
1393 || strncmp (start, "task", length) == 0)
1394 && space_then_number (lexptr))
1396 /* "task" or "thread" followed by a number terminates the
1397 parse, per gdb rules. */
1402 if (token == NULL || (parse_completion && lexptr[0] == '\0'))
1403 rustyylval.sval = make_stoken (rust_copy_name (start, length));
1405 if (parse_completion && lexptr[0] == '\0')
1407 /* Prevent rustyylex from returning two COMPLETE tokens. */
1408 prev_lexptr = lexptr;
1413 return token->value;
1419 /* Lex an operator. */
1424 const struct token_info *token = NULL;
1427 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
1429 if (strncmp (operator_tokens[i].name, lexptr,
1430 strlen (operator_tokens[i].name)) == 0)
1432 lexptr += strlen (operator_tokens[i].name);
1433 token = &operator_tokens[i];
1440 rustyylval.opcode = token->opcode;
1441 return token->value;
1452 regmatch_t subexps[NUM_SUBEXPRESSIONS];
1455 int could_be_decimal = 1;
1456 int implicit_i32 = 0;
1457 const char *type_name = NULL;
1460 int type_index = -1;
1463 match = regexec (&number_regex, lexptr, ARRAY_SIZE (subexps), subexps, 0);
1464 /* Failure means the regexp is broken. */
1465 gdb_assert (match == 0);
1467 if (subexps[INT_TEXT].rm_so != -1)
1469 /* Integer part matched. */
1471 end_index = subexps[INT_TEXT].rm_eo;
1472 if (subexps[INT_TYPE].rm_so == -1)
1479 type_index = INT_TYPE;
1480 could_be_decimal = 0;
1483 else if (subexps[FLOAT_TYPE1].rm_so != -1)
1485 /* Found floating point type suffix. */
1486 end_index = subexps[FLOAT_TYPE1].rm_so;
1487 type_index = FLOAT_TYPE1;
1489 else if (subexps[FLOAT_TYPE2].rm_so != -1)
1491 /* Found floating point type suffix. */
1492 end_index = subexps[FLOAT_TYPE2].rm_so;
1493 type_index = FLOAT_TYPE2;
1497 /* Any other floating point match. */
1498 end_index = subexps[0].rm_eo;
1502 /* We need a special case if the final character is ".". In this
1503 case we might need to parse an integer. For example, "23.f()" is
1504 a request for a trait method call, not a syntax error involving
1505 the floating point number "23.". */
1506 gdb_assert (subexps[0].rm_eo > 0);
1507 if (lexptr[subexps[0].rm_eo - 1] == '.')
1509 const char *next = skip_spaces (&lexptr[subexps[0].rm_eo]);
1511 if (rust_identifier_start_p (*next) || *next == '.')
1515 end_index = subexps[0].rm_eo;
1517 could_be_decimal = 1;
1522 /* Compute the type name if we haven't already. */
1523 std::string type_name_holder;
1524 if (type_name == NULL)
1526 gdb_assert (type_index != -1);
1527 type_name_holder = std::string (lexptr + subexps[type_index].rm_so,
1528 (subexps[type_index].rm_eo
1529 - subexps[type_index].rm_so));
1530 type_name = type_name_holder.c_str ();
1533 /* Look up the type. */
1534 type = rust_type (type_name);
1536 /* Copy the text of the number and remove the "_"s. */
1538 for (i = 0; i < end_index && lexptr[i]; ++i)
1540 if (lexptr[i] == '_')
1541 could_be_decimal = 0;
1543 number.push_back (lexptr[i]);
1546 /* Advance past the match. */
1547 lexptr += subexps[0].rm_eo;
1549 /* Parse the number. */
1556 if (number[0] == '0')
1558 if (number[1] == 'x')
1560 else if (number[1] == 'o')
1562 else if (number[1] == 'b')
1567 could_be_decimal = 0;
1571 value = strtoul (number.c_str () + offset, NULL, radix);
1572 if (implicit_i32 && value >= ((uint64_t) 1) << 31)
1573 type = rust_type ("i64");
1575 rustyylval.typed_val_int.val = value;
1576 rustyylval.typed_val_int.type = type;
1580 rustyylval.typed_val_float.type = type;
1581 bool parsed = parse_float (number.c_str (), number.length (),
1582 rustyylval.typed_val_float.type,
1583 rustyylval.typed_val_float.val);
1584 gdb_assert (parsed);
1587 return is_integer ? (could_be_decimal ? DECIMAL_INTEGER : INTEGER) : FLOAT;
1595 /* Skip all leading whitespace. */
1596 while (lexptr[0] == ' ' || lexptr[0] == '\t' || lexptr[0] == '\r'
1597 || lexptr[0] == '\n')
1600 /* If we hit EOF and we're completing, then return COMPLETE -- maybe
1601 we're completing an empty string at the end of a field_expr.
1602 But, we don't want to return two COMPLETE tokens in a row. */
1603 if (lexptr[0] == '\0' && lexptr == prev_lexptr)
1605 prev_lexptr = lexptr;
1606 if (lexptr[0] == '\0')
1608 if (parse_completion)
1610 rustyylval.sval = make_stoken ("");
1616 if (lexptr[0] >= '0' && lexptr[0] <= '9')
1617 return lex_number ();
1618 else if (lexptr[0] == 'b' && lexptr[1] == '\'')
1619 return lex_character ();
1620 else if (lexptr[0] == 'b' && lexptr[1] == '"')
1621 return lex_string ();
1622 else if (lexptr[0] == 'b' && starts_raw_string (lexptr + 1))
1623 return lex_string ();
1624 else if (starts_raw_string (lexptr))
1625 return lex_string ();
1626 else if (rust_identifier_start_p (lexptr[0]))
1627 return lex_identifier ();
1628 else if (lexptr[0] == '"')
1629 return lex_string ();
1630 else if (lexptr[0] == '\'')
1631 return lex_character ();
1632 else if (lexptr[0] == '}' || lexptr[0] == ']')
1634 /* Falls through to lex_operator. */
1637 else if (lexptr[0] == '(' || lexptr[0] == '{')
1639 /* Falls through to lex_operator. */
1642 else if (lexptr[0] == ',' && comma_terminates && paren_depth == 0)
1645 return lex_operator ();
1648 /* Push back a single character to be re-lexed. */
1651 rust_push_back (char c)
1653 /* Can't be called before any lexing. */
1654 gdb_assert (prev_lexptr != NULL);
1657 gdb_assert (*lexptr == c);
1662 /* Make an arbitrary operation and fill in the fields. */
1664 static const struct rust_op *
1665 ast_operation (enum exp_opcode opcode, const struct rust_op *left,
1666 const struct rust_op *right)
1668 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1670 result->opcode = opcode;
1671 result->left.op = left;
1672 result->right.op = right;
1677 /* Make a compound assignment operation. */
1679 static const struct rust_op *
1680 ast_compound_assignment (enum exp_opcode opcode, const struct rust_op *left,
1681 const struct rust_op *right)
1683 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1685 result->opcode = opcode;
1686 result->compound_assignment = 1;
1687 result->left.op = left;
1688 result->right.op = right;
1693 /* Make a typed integer literal operation. */
1695 static const struct rust_op *
1696 ast_literal (struct typed_val_int val)
1698 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1700 result->opcode = OP_LONG;
1701 result->left.typed_val_int = val;
1706 /* Make a typed floating point literal operation. */
1708 static const struct rust_op *
1709 ast_dliteral (struct typed_val_float val)
1711 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1713 result->opcode = OP_FLOAT;
1714 result->left.typed_val_float = val;
1719 /* Make a unary operation. */
1721 static const struct rust_op *
1722 ast_unary (enum exp_opcode opcode, const struct rust_op *expr)
1724 return ast_operation (opcode, expr, NULL);
1727 /* Make a cast operation. */
1729 static const struct rust_op *
1730 ast_cast (const struct rust_op *expr, const struct rust_op *type)
1732 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1734 result->opcode = UNOP_CAST;
1735 result->left.op = expr;
1736 result->right.op = type;
1741 /* Make a call-like operation. This is nominally a function call, but
1742 when lowering we may discover that it actually represents the
1743 creation of a tuple struct. */
1745 static const struct rust_op *
1746 ast_call_ish (enum exp_opcode opcode, const struct rust_op *expr,
1747 rust_op_vector *params)
1749 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1751 result->opcode = opcode;
1752 result->left.op = expr;
1753 result->right.params = params;
1758 /* Make a structure creation operation. */
1760 static const struct rust_op *
1761 ast_struct (const struct rust_op *name, rust_set_vector *fields)
1763 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1765 result->opcode = OP_AGGREGATE;
1766 result->left.op = name;
1767 result->right.field_inits = fields;
1772 /* Make an identifier path. */
1774 static const struct rust_op *
1775 ast_path (struct stoken path, rust_op_vector *params)
1777 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1779 result->opcode = OP_VAR_VALUE;
1780 result->left.sval = path;
1781 result->right.params = params;
1786 /* Make a string constant operation. */
1788 static const struct rust_op *
1789 ast_string (struct stoken str)
1791 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1793 result->opcode = OP_STRING;
1794 result->left.sval = str;
1799 /* Make a field expression. */
1801 static const struct rust_op *
1802 ast_structop (const struct rust_op *left, const char *name, int completing)
1804 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1806 result->opcode = STRUCTOP_STRUCT;
1807 result->completing = completing;
1808 result->left.op = left;
1809 result->right.sval = make_stoken (name);
1814 /* Make an anonymous struct operation, like 'x.0'. */
1816 static const struct rust_op *
1817 ast_structop_anonymous (const struct rust_op *left,
1818 struct typed_val_int number)
1820 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1822 result->opcode = STRUCTOP_ANONYMOUS;
1823 result->left.op = left;
1824 result->right.typed_val_int = number;
1829 /* Make a range operation. */
1831 static const struct rust_op *
1832 ast_range (const struct rust_op *lhs, const struct rust_op *rhs)
1834 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1836 result->opcode = OP_RANGE;
1837 result->left.op = lhs;
1838 result->right.op = rhs;
1843 /* A helper function to make a type-related AST node. */
1845 static struct rust_op *
1846 ast_basic_type (enum type_code typecode)
1848 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1850 result->opcode = OP_TYPE;
1851 result->typecode = typecode;
1855 /* Create an AST node describing an array type. */
1857 static const struct rust_op *
1858 ast_array_type (const struct rust_op *lhs, struct typed_val_int val)
1860 struct rust_op *result = ast_basic_type (TYPE_CODE_ARRAY);
1862 result->left.op = lhs;
1863 result->right.typed_val_int = val;
1867 /* Create an AST node describing a reference type. */
1869 static const struct rust_op *
1870 ast_slice_type (const struct rust_op *type)
1872 /* Use TYPE_CODE_COMPLEX just because it is handy. */
1873 struct rust_op *result = ast_basic_type (TYPE_CODE_COMPLEX);
1875 result->left.op = type;
1879 /* Create an AST node describing a reference type. */
1881 static const struct rust_op *
1882 ast_reference_type (const struct rust_op *type)
1884 struct rust_op *result = ast_basic_type (TYPE_CODE_REF);
1886 result->left.op = type;
1890 /* Create an AST node describing a pointer type. */
1892 static const struct rust_op *
1893 ast_pointer_type (const struct rust_op *type, int is_mut)
1895 struct rust_op *result = ast_basic_type (TYPE_CODE_PTR);
1897 result->left.op = type;
1898 /* For the time being we ignore is_mut. */
1902 /* Create an AST node describing a function type. */
1904 static const struct rust_op *
1905 ast_function_type (const struct rust_op *rtype, rust_op_vector *params)
1907 struct rust_op *result = ast_basic_type (TYPE_CODE_FUNC);
1909 result->left.op = rtype;
1910 result->right.params = params;
1914 /* Create an AST node describing a tuple type. */
1916 static const struct rust_op *
1917 ast_tuple_type (rust_op_vector *params)
1919 struct rust_op *result = ast_basic_type (TYPE_CODE_STRUCT);
1921 result->left.params = params;
1925 /* A helper to appropriately munge NAME and BLOCK depending on the
1926 presence of a leading "::". */
1929 munge_name_and_block (const char **name, const struct block **block)
1931 /* If it is a global reference, skip the current block in favor of
1932 the static block. */
1933 if (strncmp (*name, "::", 2) == 0)
1936 *block = block_static_block (*block);
1940 /* Like lookup_symbol, but handles Rust namespace conventions, and
1941 doesn't require field_of_this_result. */
1943 static struct block_symbol
1944 rust_lookup_symbol (const char *name, const struct block *block,
1945 const domain_enum domain)
1947 struct block_symbol result;
1949 munge_name_and_block (&name, &block);
1951 result = lookup_symbol (name, block, domain, NULL);
1952 if (result.symbol != NULL)
1953 update_innermost_block (result);
1957 /* Look up a type, following Rust namespace conventions. */
1959 static struct type *
1960 rust_lookup_type (const char *name, const struct block *block)
1962 struct block_symbol result;
1965 munge_name_and_block (&name, &block);
1967 result = lookup_symbol (name, block, STRUCT_DOMAIN, NULL);
1968 if (result.symbol != NULL)
1970 update_innermost_block (result);
1971 return SYMBOL_TYPE (result.symbol);
1974 type = lookup_typename (current_parser->language (), current_parser->arch (),
1979 /* Last chance, try a built-in type. */
1980 return language_lookup_primitive_type (current_parser->language (),
1981 current_parser->arch (),
1985 static struct type *convert_ast_to_type (struct parser_state *state,
1986 const struct rust_op *operation);
1987 static const char *convert_name (struct parser_state *state,
1988 const struct rust_op *operation);
1990 /* Convert a vector of rust_ops representing types to a vector of
1993 static std::vector<struct type *>
1994 convert_params_to_types (struct parser_state *state, rust_op_vector *params)
1996 std::vector<struct type *> result;
1998 for (const rust_op *op : *params)
1999 result.push_back (convert_ast_to_type (state, op));
2004 /* Convert a rust_op representing a type to a struct type *. */
2006 static struct type *
2007 convert_ast_to_type (struct parser_state *state,
2008 const struct rust_op *operation)
2010 struct type *type, *result = NULL;
2012 if (operation->opcode == OP_VAR_VALUE)
2014 const char *varname = convert_name (state, operation);
2016 result = rust_lookup_type (varname, expression_context_block);
2018 error (_("No typed name '%s' in current context"), varname);
2022 gdb_assert (operation->opcode == OP_TYPE);
2024 switch (operation->typecode)
2026 case TYPE_CODE_ARRAY:
2027 type = convert_ast_to_type (state, operation->left.op);
2028 if (operation->right.typed_val_int.val < 0)
2029 error (_("Negative array length"));
2030 result = lookup_array_range_type (type, 0,
2031 operation->right.typed_val_int.val - 1);
2034 case TYPE_CODE_COMPLEX:
2036 struct type *usize = rust_type ("usize");
2038 type = convert_ast_to_type (state, operation->left.op);
2039 result = rust_slice_type ("&[*gdb*]", type, usize);
2045 /* For now we treat &x and *x identically. */
2046 type = convert_ast_to_type (state, operation->left.op);
2047 result = lookup_pointer_type (type);
2050 case TYPE_CODE_FUNC:
2052 std::vector<struct type *> args
2053 (convert_params_to_types (state, operation->right.params));
2054 struct type **argtypes = NULL;
2056 type = convert_ast_to_type (state, operation->left.op);
2058 argtypes = args.data ();
2061 = lookup_function_type_with_arguments (type, args.size (),
2063 result = lookup_pointer_type (result);
2067 case TYPE_CODE_STRUCT:
2069 std::vector<struct type *> args
2070 (convert_params_to_types (state, operation->left.params));
2075 obstack_1grow (work_obstack, '(');
2076 for (i = 0; i < args.size (); ++i)
2078 std::string type_name = type_to_string (args[i]);
2081 obstack_1grow (work_obstack, ',');
2082 obstack_grow_str (work_obstack, type_name.c_str ());
2085 obstack_grow_str0 (work_obstack, ")");
2086 name = (const char *) obstack_finish (work_obstack);
2088 /* We don't allow creating new tuple types (yet), but we do
2089 allow looking up existing tuple types. */
2090 result = rust_lookup_type (name, expression_context_block);
2092 error (_("could not find tuple type '%s'"), name);
2097 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_type");
2100 gdb_assert (result != NULL);
2104 /* A helper function to turn a rust_op representing a name into a full
2105 name. This applies generic arguments as needed. The returned name
2106 is allocated on the work obstack. */
2109 convert_name (struct parser_state *state, const struct rust_op *operation)
2113 gdb_assert (operation->opcode == OP_VAR_VALUE);
2115 if (operation->right.params == NULL)
2116 return operation->left.sval.ptr;
2118 std::vector<struct type *> types
2119 (convert_params_to_types (state, operation->right.params));
2121 obstack_grow_str (work_obstack, operation->left.sval.ptr);
2122 obstack_1grow (work_obstack, '<');
2123 for (i = 0; i < types.size (); ++i)
2125 std::string type_name = type_to_string (types[i]);
2128 obstack_1grow (work_obstack, ',');
2130 obstack_grow_str (work_obstack, type_name.c_str ());
2132 obstack_grow_str0 (work_obstack, ">");
2134 return (const char *) obstack_finish (work_obstack);
2137 static void convert_ast_to_expression (struct parser_state *state,
2138 const struct rust_op *operation,
2139 const struct rust_op *top,
2140 bool want_type = false);
2142 /* A helper function that converts a vec of rust_ops to a gdb
2146 convert_params_to_expression (struct parser_state *state,
2147 rust_op_vector *params,
2148 const struct rust_op *top)
2150 for (const rust_op *elem : *params)
2151 convert_ast_to_expression (state, elem, top);
2154 /* Lower a rust_op to a gdb expression. STATE is the parser state.
2155 OPERATION is the operation to lower. TOP is a pointer to the
2156 top-most operation; it is used to handle the special case where the
2157 top-most expression is an identifier and can be optionally lowered
2158 to OP_TYPE. WANT_TYPE is a flag indicating that, if the expression
2159 is the name of a type, then emit an OP_TYPE for it (rather than
2160 erroring). If WANT_TYPE is set, then the similar TOP handling is
2164 convert_ast_to_expression (struct parser_state *state,
2165 const struct rust_op *operation,
2166 const struct rust_op *top,
2169 switch (operation->opcode)
2172 write_exp_elt_opcode (state, OP_LONG);
2173 write_exp_elt_type (state, operation->left.typed_val_int.type);
2174 write_exp_elt_longcst (state, operation->left.typed_val_int.val);
2175 write_exp_elt_opcode (state, OP_LONG);
2179 write_exp_elt_opcode (state, OP_FLOAT);
2180 write_exp_elt_type (state, operation->left.typed_val_float.type);
2181 write_exp_elt_floatcst (state, operation->left.typed_val_float.val);
2182 write_exp_elt_opcode (state, OP_FLOAT);
2185 case STRUCTOP_STRUCT:
2187 convert_ast_to_expression (state, operation->left.op, top);
2189 if (operation->completing)
2190 mark_struct_expression (state);
2191 write_exp_elt_opcode (state, STRUCTOP_STRUCT);
2192 write_exp_string (state, operation->right.sval);
2193 write_exp_elt_opcode (state, STRUCTOP_STRUCT);
2197 case STRUCTOP_ANONYMOUS:
2199 convert_ast_to_expression (state, operation->left.op, top);
2201 write_exp_elt_opcode (state, STRUCTOP_ANONYMOUS);
2202 write_exp_elt_longcst (state, operation->right.typed_val_int.val);
2203 write_exp_elt_opcode (state, STRUCTOP_ANONYMOUS);
2208 convert_ast_to_expression (state, operation->left.op, top, true);
2209 write_exp_elt_opcode (state, UNOP_SIZEOF);
2214 case UNOP_COMPLEMENT:
2217 convert_ast_to_expression (state, operation->left.op, top);
2218 write_exp_elt_opcode (state, operation->opcode);
2221 case BINOP_SUBSCRIPT:
2228 case BINOP_BITWISE_AND:
2229 case BINOP_BITWISE_IOR:
2230 case BINOP_BITWISE_XOR:
2233 case BINOP_LOGICAL_OR:
2234 case BINOP_LOGICAL_AND:
2236 case BINOP_NOTEQUAL:
2243 convert_ast_to_expression (state, operation->left.op, top);
2244 convert_ast_to_expression (state, operation->right.op, top);
2245 if (operation->compound_assignment)
2247 write_exp_elt_opcode (state, BINOP_ASSIGN_MODIFY);
2248 write_exp_elt_opcode (state, operation->opcode);
2249 write_exp_elt_opcode (state, BINOP_ASSIGN_MODIFY);
2252 write_exp_elt_opcode (state, operation->opcode);
2254 if (operation->compound_assignment
2255 || operation->opcode == BINOP_ASSIGN)
2259 type = language_lookup_primitive_type (parse_language (state),
2260 parse_gdbarch (state),
2263 write_exp_elt_opcode (state, OP_LONG);
2264 write_exp_elt_type (state, type);
2265 write_exp_elt_longcst (state, 0);
2266 write_exp_elt_opcode (state, OP_LONG);
2268 write_exp_elt_opcode (state, BINOP_COMMA);
2274 struct type *type = convert_ast_to_type (state, operation->right.op);
2276 convert_ast_to_expression (state, operation->left.op, top);
2277 write_exp_elt_opcode (state, UNOP_CAST);
2278 write_exp_elt_type (state, type);
2279 write_exp_elt_opcode (state, UNOP_CAST);
2285 if (operation->left.op->opcode == OP_VAR_VALUE)
2288 const char *varname = convert_name (state, operation->left.op);
2290 type = rust_lookup_type (varname, expression_context_block);
2293 /* This is actually a tuple struct expression, not a
2295 rust_op_vector *params = operation->right.params;
2297 if (TYPE_CODE (type) != TYPE_CODE_NAMESPACE)
2299 if (!rust_tuple_struct_type_p (type))
2300 error (_("Type %s is not a tuple struct"), varname);
2302 for (int i = 0; i < params->size (); ++i)
2304 char *cell = get_print_cell ();
2306 xsnprintf (cell, PRINT_CELL_SIZE, "__%d", i);
2307 write_exp_elt_opcode (state, OP_NAME);
2308 write_exp_string (state, make_stoken (cell));
2309 write_exp_elt_opcode (state, OP_NAME);
2311 convert_ast_to_expression (state, (*params)[i], top);
2314 write_exp_elt_opcode (state, OP_AGGREGATE);
2315 write_exp_elt_type (state, type);
2316 write_exp_elt_longcst (state, 2 * params->size ());
2317 write_exp_elt_opcode (state, OP_AGGREGATE);
2322 convert_ast_to_expression (state, operation->left.op, top);
2323 convert_params_to_expression (state, operation->right.params, top);
2324 write_exp_elt_opcode (state, OP_FUNCALL);
2325 write_exp_elt_longcst (state, operation->right.params->size ());
2326 write_exp_elt_longcst (state, OP_FUNCALL);
2331 gdb_assert (operation->left.op == NULL);
2332 convert_params_to_expression (state, operation->right.params, top);
2333 write_exp_elt_opcode (state, OP_ARRAY);
2334 write_exp_elt_longcst (state, 0);
2335 write_exp_elt_longcst (state, operation->right.params->size () - 1);
2336 write_exp_elt_longcst (state, OP_ARRAY);
2341 struct block_symbol sym;
2342 const char *varname;
2344 if (operation->left.sval.ptr[0] == '$')
2346 write_dollar_variable (state, operation->left.sval);
2350 varname = convert_name (state, operation);
2351 sym = rust_lookup_symbol (varname, expression_context_block,
2353 if (sym.symbol != NULL && SYMBOL_CLASS (sym.symbol) != LOC_TYPEDEF)
2355 write_exp_elt_opcode (state, OP_VAR_VALUE);
2356 write_exp_elt_block (state, sym.block);
2357 write_exp_elt_sym (state, sym.symbol);
2358 write_exp_elt_opcode (state, OP_VAR_VALUE);
2362 struct type *type = NULL;
2364 if (sym.symbol != NULL)
2366 gdb_assert (SYMBOL_CLASS (sym.symbol) == LOC_TYPEDEF);
2367 type = SYMBOL_TYPE (sym.symbol);
2370 type = rust_lookup_type (varname, expression_context_block);
2372 error (_("No symbol '%s' in current context"), varname);
2375 && TYPE_CODE (type) == TYPE_CODE_STRUCT
2376 && TYPE_NFIELDS (type) == 0)
2378 /* A unit-like struct. */
2379 write_exp_elt_opcode (state, OP_AGGREGATE);
2380 write_exp_elt_type (state, type);
2381 write_exp_elt_longcst (state, 0);
2382 write_exp_elt_opcode (state, OP_AGGREGATE);
2384 else if (want_type || operation == top)
2386 write_exp_elt_opcode (state, OP_TYPE);
2387 write_exp_elt_type (state, type);
2388 write_exp_elt_opcode (state, OP_TYPE);
2391 error (_("Found type '%s', which can't be "
2392 "evaluated in this context"),
2402 rust_set_vector *fields = operation->right.field_inits;
2407 for (const set_field &init : *fields)
2409 if (init.name.ptr != NULL)
2411 write_exp_elt_opcode (state, OP_NAME);
2412 write_exp_string (state, init.name);
2413 write_exp_elt_opcode (state, OP_NAME);
2417 convert_ast_to_expression (state, init.init, top);
2420 if (init.name.ptr == NULL)
2422 /* This is handled differently from Ada in our
2424 write_exp_elt_opcode (state, OP_OTHERS);
2428 name = convert_name (state, operation->left.op);
2429 type = rust_lookup_type (name, expression_context_block);
2431 error (_("Could not find type '%s'"), operation->left.sval.ptr);
2433 if (TYPE_CODE (type) != TYPE_CODE_STRUCT
2434 || rust_tuple_type_p (type)
2435 || rust_tuple_struct_type_p (type))
2436 error (_("Struct expression applied to non-struct type"));
2438 write_exp_elt_opcode (state, OP_AGGREGATE);
2439 write_exp_elt_type (state, type);
2440 write_exp_elt_longcst (state, length);
2441 write_exp_elt_opcode (state, OP_AGGREGATE);
2447 write_exp_elt_opcode (state, OP_STRING);
2448 write_exp_string (state, operation->left.sval);
2449 write_exp_elt_opcode (state, OP_STRING);
2455 enum range_type kind = BOTH_BOUND_DEFAULT;
2457 if (operation->left.op != NULL)
2459 convert_ast_to_expression (state, operation->left.op, top);
2460 kind = HIGH_BOUND_DEFAULT;
2462 if (operation->right.op != NULL)
2464 convert_ast_to_expression (state, operation->right.op, top);
2465 if (kind == BOTH_BOUND_DEFAULT)
2466 kind = LOW_BOUND_DEFAULT;
2469 gdb_assert (kind == HIGH_BOUND_DEFAULT);
2470 kind = NONE_BOUND_DEFAULT;
2473 write_exp_elt_opcode (state, OP_RANGE);
2474 write_exp_elt_longcst (state, kind);
2475 write_exp_elt_opcode (state, OP_RANGE);
2480 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_expression");
2486 /* The parser as exposed to gdb. */
2489 rust_parse (struct parser_state *state)
2493 /* This sets various globals and also clears them on
2495 rust_parser parser (state);
2497 result = rustyyparse ();
2499 if (!result || (parse_completion && parser.rust_ast != NULL))
2500 convert_ast_to_expression (state, parser.rust_ast, parser.rust_ast);
2505 /* The parser error handler. */
2508 rustyyerror (const char *msg)
2510 const char *where = prev_lexptr ? prev_lexptr : lexptr;
2511 error (_("%s in expression, near `%s'."), (msg ? msg : "Error"), where);
2518 /* Initialize the lexer for testing. */
2521 rust_lex_test_init (const char *input)
2528 /* A test helper that lexes a string, expecting a single token. It
2529 returns the lexer data for this token. */
2532 rust_lex_test_one (const char *input, int expected)
2537 rust_lex_test_init (input);
2539 token = rustyylex ();
2540 SELF_CHECK (token == expected);
2541 result = rustyylval;
2545 token = rustyylex ();
2546 SELF_CHECK (token == 0);
2552 /* Test that INPUT lexes as the integer VALUE. */
2555 rust_lex_int_test (const char *input, int value, int kind)
2557 RUSTSTYPE result = rust_lex_test_one (input, kind);
2558 SELF_CHECK (result.typed_val_int.val == value);
2561 /* Test that INPUT throws an exception with text ERR. */
2564 rust_lex_exception_test (const char *input, const char *err)
2568 /* The "kind" doesn't matter. */
2569 rust_lex_test_one (input, DECIMAL_INTEGER);
2572 CATCH (except, RETURN_MASK_ERROR)
2574 SELF_CHECK (strcmp (except.message, err) == 0);
2579 /* Test that INPUT lexes as the identifier, string, or byte-string
2580 VALUE. KIND holds the expected token kind. */
2583 rust_lex_stringish_test (const char *input, const char *value, int kind)
2585 RUSTSTYPE result = rust_lex_test_one (input, kind);
2586 SELF_CHECK (result.sval.length == strlen (value));
2587 SELF_CHECK (strncmp (result.sval.ptr, value, result.sval.length) == 0);
2590 /* Helper to test that a string parses as a given token sequence. */
2593 rust_lex_test_sequence (const char *input, int len, const int expected[])
2600 for (i = 0; i < len; ++i)
2602 int token = rustyylex ();
2604 SELF_CHECK (token == expected[i]);
2608 /* Tests for an integer-parsing corner case. */
2611 rust_lex_test_trailing_dot (void)
2613 const int expected1[] = { DECIMAL_INTEGER, '.', IDENT, '(', ')', 0 };
2614 const int expected2[] = { INTEGER, '.', IDENT, '(', ')', 0 };
2615 const int expected3[] = { FLOAT, EQEQ, '(', ')', 0 };
2616 const int expected4[] = { DECIMAL_INTEGER, DOTDOT, DECIMAL_INTEGER, 0 };
2618 rust_lex_test_sequence ("23.g()", ARRAY_SIZE (expected1), expected1);
2619 rust_lex_test_sequence ("23_0.g()", ARRAY_SIZE (expected2), expected2);
2620 rust_lex_test_sequence ("23.==()", ARRAY_SIZE (expected3), expected3);
2621 rust_lex_test_sequence ("23..25", ARRAY_SIZE (expected4), expected4);
2624 /* Tests of completion. */
2627 rust_lex_test_completion (void)
2629 const int expected[] = { IDENT, '.', COMPLETE, 0 };
2631 parse_completion = 1;
2633 rust_lex_test_sequence ("something.wha", ARRAY_SIZE (expected), expected);
2634 rust_lex_test_sequence ("something.", ARRAY_SIZE (expected), expected);
2636 parse_completion = 0;
2639 /* Test pushback. */
2642 rust_lex_test_push_back (void)
2646 rust_lex_test_init (">>=");
2648 token = rustyylex ();
2649 SELF_CHECK (token == COMPOUND_ASSIGN);
2650 SELF_CHECK (rustyylval.opcode == BINOP_RSH);
2652 rust_push_back ('=');
2654 token = rustyylex ();
2655 SELF_CHECK (token == '=');
2657 token = rustyylex ();
2658 SELF_CHECK (token == 0);
2661 /* Unit test the lexer. */
2664 rust_lex_tests (void)
2668 auto_obstack test_obstack;
2669 scoped_restore obstack_holder = make_scoped_restore (&work_obstack,
2672 // Set up dummy "parser", so that rust_type works.
2673 struct parser_state ps;
2674 initialize_expout (&ps, 0, &rust_language_defn, target_gdbarch ());
2675 rust_parser parser (&ps);
2677 rust_lex_test_one ("", 0);
2678 rust_lex_test_one (" \t \n \r ", 0);
2679 rust_lex_test_one ("thread 23", 0);
2680 rust_lex_test_one ("task 23", 0);
2681 rust_lex_test_one ("th 104", 0);
2682 rust_lex_test_one ("ta 97", 0);
2684 rust_lex_int_test ("'z'", 'z', INTEGER);
2685 rust_lex_int_test ("'\\xff'", 0xff, INTEGER);
2686 rust_lex_int_test ("'\\u{1016f}'", 0x1016f, INTEGER);
2687 rust_lex_int_test ("b'z'", 'z', INTEGER);
2688 rust_lex_int_test ("b'\\xfe'", 0xfe, INTEGER);
2689 rust_lex_int_test ("b'\\xFE'", 0xfe, INTEGER);
2690 rust_lex_int_test ("b'\\xfE'", 0xfe, INTEGER);
2692 /* Test all escapes in both modes. */
2693 rust_lex_int_test ("'\\n'", '\n', INTEGER);
2694 rust_lex_int_test ("'\\r'", '\r', INTEGER);
2695 rust_lex_int_test ("'\\t'", '\t', INTEGER);
2696 rust_lex_int_test ("'\\\\'", '\\', INTEGER);
2697 rust_lex_int_test ("'\\0'", '\0', INTEGER);
2698 rust_lex_int_test ("'\\''", '\'', INTEGER);
2699 rust_lex_int_test ("'\\\"'", '"', INTEGER);
2701 rust_lex_int_test ("b'\\n'", '\n', INTEGER);
2702 rust_lex_int_test ("b'\\r'", '\r', INTEGER);
2703 rust_lex_int_test ("b'\\t'", '\t', INTEGER);
2704 rust_lex_int_test ("b'\\\\'", '\\', INTEGER);
2705 rust_lex_int_test ("b'\\0'", '\0', INTEGER);
2706 rust_lex_int_test ("b'\\''", '\'', INTEGER);
2707 rust_lex_int_test ("b'\\\"'", '"', INTEGER);
2709 rust_lex_exception_test ("'z", "Unterminated character literal");
2710 rust_lex_exception_test ("b'\\x0'", "Not enough hex digits seen");
2711 rust_lex_exception_test ("b'\\u{0}'", "Unicode escape in byte literal");
2712 rust_lex_exception_test ("'\\x0'", "Not enough hex digits seen");
2713 rust_lex_exception_test ("'\\u0'", "Missing '{' in Unicode escape");
2714 rust_lex_exception_test ("'\\u{0", "Missing '}' in Unicode escape");
2715 rust_lex_exception_test ("'\\u{0000007}", "Overlong hex escape");
2716 rust_lex_exception_test ("'\\u{}", "Not enough hex digits seen");
2717 rust_lex_exception_test ("'\\Q'", "Invalid escape \\Q in literal");
2718 rust_lex_exception_test ("b'\\Q'", "Invalid escape \\Q in literal");
2720 rust_lex_int_test ("23", 23, DECIMAL_INTEGER);
2721 rust_lex_int_test ("2_344__29", 234429, INTEGER);
2722 rust_lex_int_test ("0x1f", 0x1f, INTEGER);
2723 rust_lex_int_test ("23usize", 23, INTEGER);
2724 rust_lex_int_test ("23i32", 23, INTEGER);
2725 rust_lex_int_test ("0x1_f", 0x1f, INTEGER);
2726 rust_lex_int_test ("0b1_101011__", 0x6b, INTEGER);
2727 rust_lex_int_test ("0o001177i64", 639, INTEGER);
2729 rust_lex_test_trailing_dot ();
2731 rust_lex_test_one ("23.", FLOAT);
2732 rust_lex_test_one ("23.99f32", FLOAT);
2733 rust_lex_test_one ("23e7", FLOAT);
2734 rust_lex_test_one ("23E-7", FLOAT);
2735 rust_lex_test_one ("23e+7", FLOAT);
2736 rust_lex_test_one ("23.99e+7f64", FLOAT);
2737 rust_lex_test_one ("23.82f32", FLOAT);
2739 rust_lex_stringish_test ("hibob", "hibob", IDENT);
2740 rust_lex_stringish_test ("hibob__93", "hibob__93", IDENT);
2741 rust_lex_stringish_test ("thread", "thread", IDENT);
2743 rust_lex_stringish_test ("\"string\"", "string", STRING);
2744 rust_lex_stringish_test ("\"str\\ting\"", "str\ting", STRING);
2745 rust_lex_stringish_test ("\"str\\\"ing\"", "str\"ing", STRING);
2746 rust_lex_stringish_test ("r\"str\\ing\"", "str\\ing", STRING);
2747 rust_lex_stringish_test ("r#\"str\\ting\"#", "str\\ting", STRING);
2748 rust_lex_stringish_test ("r###\"str\\\"ing\"###", "str\\\"ing", STRING);
2750 rust_lex_stringish_test ("b\"string\"", "string", BYTESTRING);
2751 rust_lex_stringish_test ("b\"\x73tring\"", "string", BYTESTRING);
2752 rust_lex_stringish_test ("b\"str\\\"ing\"", "str\"ing", BYTESTRING);
2753 rust_lex_stringish_test ("br####\"\\x73tring\"####", "\\x73tring",
2756 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
2757 rust_lex_test_one (identifier_tokens[i].name, identifier_tokens[i].value);
2759 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
2760 rust_lex_test_one (operator_tokens[i].name, operator_tokens[i].value);
2762 rust_lex_test_completion ();
2763 rust_lex_test_push_back ();
2766 #endif /* GDB_SELF_TEST */
2769 _initialize_rust_exp (void)
2771 int code = regcomp (&number_regex, number_regex_text, REG_EXTENDED);
2772 /* If the regular expression was incorrect, it was a programming
2774 gdb_assert (code == 0);
2777 selftests::register_test ("rust-lex", rust_lex_tests);