1 /* Bison parser for Rust expressions, for GDB.
2 Copyright (C) 2016-2018 Free Software Foundation, Inc.
4 This file is part of GDB.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 /* 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 rustyyerror (const char *msg);
74 static void rust_push_back (char c);
75 static const char *rust_copy_name (const char *, int);
76 static struct stoken rust_concat3 (const char *, const char *, const char *);
77 static struct stoken make_stoken (const char *);
78 static struct block_symbol rust_lookup_symbol (const char *name,
79 const struct block *block,
80 const domain_enum domain);
81 static struct type *rust_lookup_type (const char *name,
82 const struct block *block);
83 static struct type *rust_type (const char *name);
85 static const struct rust_op *crate_name (const struct rust_op *name);
86 static const struct rust_op *super_name (const struct rust_op *name,
87 unsigned int n_supers);
89 static const struct rust_op *ast_operation (enum exp_opcode opcode,
90 const struct rust_op *left,
91 const struct rust_op *right);
92 static const struct rust_op *ast_compound_assignment
93 (enum exp_opcode opcode, const struct rust_op *left,
94 const struct rust_op *rust_op);
95 static const struct rust_op *ast_literal (struct typed_val_int val);
96 static const struct rust_op *ast_dliteral (struct typed_val_float val);
97 static const struct rust_op *ast_structop (const struct rust_op *left,
100 static const struct rust_op *ast_structop_anonymous
101 (const struct rust_op *left, struct typed_val_int number);
102 static const struct rust_op *ast_unary (enum exp_opcode opcode,
103 const struct rust_op *expr);
104 static const struct rust_op *ast_cast (const struct rust_op *expr,
105 const struct rust_op *type);
106 static const struct rust_op *ast_call_ish (enum exp_opcode opcode,
107 const struct rust_op *expr,
108 rust_op_vector *params);
109 static const struct rust_op *ast_path (struct stoken name,
110 rust_op_vector *params);
111 static const struct rust_op *ast_string (struct stoken str);
112 static const struct rust_op *ast_struct (const struct rust_op *name,
113 rust_set_vector *fields);
114 static const struct rust_op *ast_range (const struct rust_op *lhs,
115 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 /* Obstack for data temporarily allocated during parsing. Points to
179 the obstack in the rust_parser, or to a temporary obstack during
182 static auto_obstack *work_obstack;
184 /* An instance of this is created before parsing, and destroyed when
185 parsing is finished. */
189 rust_parser (struct parser_state *state)
190 : rust_ast (nullptr),
193 gdb_assert (current_parser == nullptr);
194 current_parser = this;
195 work_obstack = &obstack;
200 /* Clean up the globals we set. */
201 current_parser = nullptr;
202 work_obstack = nullptr;
205 /* Create a new rust_set_vector. The storage for the new vector is
206 managed by this class. */
207 rust_set_vector *new_set_vector ()
209 rust_set_vector *result = new rust_set_vector;
210 set_vectors.push_back (std::unique_ptr<rust_set_vector> (result));
214 /* Create a new rust_ops_vector. The storage for the new vector is
215 managed by this class. */
216 rust_op_vector *new_op_vector ()
218 rust_op_vector *result = new rust_op_vector;
219 op_vectors.push_back (std::unique_ptr<rust_op_vector> (result));
223 /* Return the parser's language. */
224 const struct language_defn *language () const
226 return parse_language (pstate);
229 /* Return the parser's gdbarch. */
230 struct gdbarch *arch () const
232 return parse_gdbarch (pstate);
235 /* A pointer to this is installed globally. */
236 auto_obstack obstack;
238 /* Result of parsing. Points into obstack. */
239 const struct rust_op *rust_ast;
241 /* This keeps track of the various vectors we allocate. */
242 std::vector<std::unique_ptr<rust_set_vector>> set_vectors;
243 std::vector<std::unique_ptr<rust_op_vector>> op_vectors;
245 /* The parser state gdb gave us. */
246 struct parser_state *pstate;
253 /* A typed integer constant. */
254 struct typed_val_int typed_val_int;
256 /* A typed floating point constant. */
257 struct typed_val_float typed_val_float;
259 /* An identifier or string. */
262 /* A token representing an opcode, like "==". */
263 enum exp_opcode opcode;
265 /* A list of expressions; for example, the arguments to a function
267 rust_op_vector *params;
269 /* A list of field initializers. */
270 rust_set_vector *field_inits;
272 /* A single field initializer. */
273 struct set_field one_field_init;
276 const struct rust_op *op;
278 /* A plain integer, for example used to count the number of
279 "super::" prefixes on a path. */
285 /* Rust AST operations. We build a tree of these; then lower them
286 to gdb expressions when parsing has completed. */
291 enum exp_opcode opcode;
292 /* If OPCODE is OP_TYPE, then this holds information about what type
293 is described by this node. */
294 enum type_code typecode;
295 /* Indicates whether OPCODE actually represents a compound
296 assignment. For example, if OPCODE is GTGT and this is false,
297 then this rust_op represents an ordinary ">>"; but if this is
298 true, then this rust_op represents ">>=". Unused in other
300 unsigned int compound_assignment : 1;
301 /* Only used by a field expression; if set, indicates that the field
302 name occurred at the end of the expression and is eligible for
304 unsigned int completing : 1;
305 /* For OP_RANGE, indicates whether the range is inclusive or
307 unsigned int inclusive : 1;
308 /* Operands of expression. Which one is used and how depends on the
309 particular opcode. */
318 %token <sval> COMPLETE
319 %token <typed_val_int> INTEGER
320 %token <typed_val_int> DECIMAL_INTEGER
322 %token <sval> BYTESTRING
323 %token <typed_val_float> FLOAT
324 %token <opcode> COMPOUND_ASSIGN
326 /* Keyword tokens. */
327 %token <voidval> KW_AS
328 %token <voidval> KW_IF
329 %token <voidval> KW_TRUE
330 %token <voidval> KW_FALSE
331 %token <voidval> KW_SUPER
332 %token <voidval> KW_SELF
333 %token <voidval> KW_MUT
334 %token <voidval> KW_EXTERN
335 %token <voidval> KW_CONST
336 %token <voidval> KW_FN
337 %token <voidval> KW_SIZEOF
339 /* Operator tokens. */
340 %token <voidval> DOTDOT
341 %token <voidval> DOTDOTEQ
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
391 %nonassoc DOTDOT DOTDOTEQ
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
442 '(' expr ',' maybe_expr_list ')'
445 error (_("Tuple expressions not supported yet"));
452 struct typed_val_int val;
455 = (language_lookup_primitive_type
456 (current_parser->language (), current_parser->arch (),
459 $$ = ast_literal (val);
463 /* To avoid a shift/reduce conflict with call_expr, we don't handle
464 tuple struct expressions here, but instead when examining the
467 path_for_expr '{' struct_expr_list '}'
468 { $$ = ast_struct ($1, $3); }
495 sf.init = ast_path ($1, NULL);
503 $$ = current_parser->new_set_vector ();
507 rust_set_vector *result = current_parser->new_set_vector ();
508 result->push_back ($1);
511 | IDENT ':' expr ',' struct_expr_list
520 | IDENT ',' struct_expr_list
525 sf.init = ast_path ($1, NULL);
532 '[' KW_MUT expr_list ']'
533 { $$ = ast_call_ish (OP_ARRAY, NULL, $3); }
535 { $$ = ast_call_ish (OP_ARRAY, NULL, $2); }
536 | '[' KW_MUT expr ';' expr ']'
537 { $$ = ast_operation (OP_RUST_ARRAY, $3, $5); }
538 | '[' expr ';' expr ']'
539 { $$ = ast_operation (OP_RUST_ARRAY, $2, $4); }
544 { $$ = ast_range ($1, NULL, false); }
546 { $$ = ast_range ($1, $3, false); }
548 { $$ = ast_range ($1, $3, true); }
550 { $$ = ast_range (NULL, $2, false); }
552 { $$ = ast_range (NULL, $2, true); }
554 { $$ = ast_range (NULL, NULL, false); }
559 { $$ = ast_literal ($1); }
561 { $$ = ast_literal ($1); }
563 { $$ = ast_dliteral ($1); }
566 const struct rust_op *str = ast_string ($1);
567 struct set_field field;
568 struct typed_val_int val;
571 rust_set_vector *fields = current_parser->new_set_vector ();
573 /* Wrap the raw string in the &str struct. */
574 field.name.ptr = "data_ptr";
575 field.name.length = strlen (field.name.ptr);
576 field.init = ast_unary (UNOP_ADDR, ast_string ($1));
577 fields->push_back (field);
579 val.type = rust_type ("usize");
582 field.name.ptr = "length";
583 field.name.length = strlen (field.name.ptr);
584 field.init = ast_literal (val);
585 fields->push_back (field);
588 token.length = strlen (token.ptr);
589 $$ = ast_struct (ast_path (token, NULL), fields);
592 { $$ = ast_string ($1); }
595 struct typed_val_int val;
597 val.type = language_bool_type (current_parser->language (),
598 current_parser->arch ());
600 $$ = ast_literal (val);
604 struct typed_val_int val;
606 val.type = language_bool_type (current_parser->language (),
607 current_parser->arch ());
609 $$ = ast_literal (val);
615 { $$ = ast_structop ($1, $3.ptr, 0); }
618 $$ = ast_structop ($1, $3.ptr, 1);
619 current_parser->rust_ast = $$;
621 | expr '.' DECIMAL_INTEGER
622 { $$ = ast_structop_anonymous ($1, $3); }
627 { $$ = ast_operation (BINOP_SUBSCRIPT, $1, $3); }
632 { $$ = ast_unary (UNOP_PLUS, $2); }
634 | '-' expr %prec UNARY
635 { $$ = ast_unary (UNOP_NEG, $2); }
637 | '!' expr %prec UNARY
639 /* Note that we provide a Rust-specific evaluator
640 override for UNOP_COMPLEMENT, so it can do the
641 right thing for both bool and integral
643 $$ = ast_unary (UNOP_COMPLEMENT, $2);
646 | '*' expr %prec UNARY
647 { $$ = ast_unary (UNOP_IND, $2); }
649 | '&' expr %prec UNARY
650 { $$ = ast_unary (UNOP_ADDR, $2); }
652 | '&' KW_MUT expr %prec UNARY
653 { $$ = ast_unary (UNOP_ADDR, $3); }
654 | KW_SIZEOF '(' expr ')' %prec UNARY
655 { $$ = ast_unary (UNOP_SIZEOF, $3); }
662 | compound_assignment_expr
667 { $$ = ast_operation (BINOP_MUL, $1, $3); }
670 { $$ = ast_operation (BINOP_REPEAT, $1, $3); }
673 { $$ = ast_operation (BINOP_DIV, $1, $3); }
676 { $$ = ast_operation (BINOP_REM, $1, $3); }
679 { $$ = ast_operation (BINOP_LESS, $1, $3); }
682 { $$ = ast_operation (BINOP_GTR, $1, $3); }
685 { $$ = ast_operation (BINOP_BITWISE_AND, $1, $3); }
688 { $$ = ast_operation (BINOP_BITWISE_IOR, $1, $3); }
691 { $$ = ast_operation (BINOP_BITWISE_XOR, $1, $3); }
694 { $$ = ast_operation (BINOP_ADD, $1, $3); }
697 { $$ = ast_operation (BINOP_SUB, $1, $3); }
700 { $$ = ast_operation (BINOP_LOGICAL_OR, $1, $3); }
703 { $$ = ast_operation (BINOP_LOGICAL_AND, $1, $3); }
706 { $$ = ast_operation (BINOP_EQUAL, $1, $3); }
709 { $$ = ast_operation (BINOP_NOTEQUAL, $1, $3); }
712 { $$ = ast_operation (BINOP_LEQ, $1, $3); }
715 { $$ = ast_operation (BINOP_GEQ, $1, $3); }
718 { $$ = ast_operation (BINOP_LSH, $1, $3); }
721 { $$ = ast_operation (BINOP_RSH, $1, $3); }
726 { $$ = ast_cast ($1, $3); }
731 { $$ = ast_operation (BINOP_ASSIGN, $1, $3); }
734 compound_assignment_expr:
735 expr COMPOUND_ASSIGN expr
736 { $$ = ast_compound_assignment ($2, $1, $3); }
748 $$ = current_parser->new_op_vector ();
761 /* The result can't be NULL. */
762 $$ = current_parser->new_op_vector ();
769 '(' maybe_expr_list ')'
775 { $$ = ast_call_ish (OP_FUNCALL, $1, $2); }
786 | super_path KW_SUPER COLONCOLON
794 { $$ = ast_path ($1, NULL); }
796 { $$ = ast_path (make_stoken ("self"), NULL); }
800 identifier_path_for_expr
801 | KW_SELF COLONCOLON identifier_path_for_expr
802 { $$ = super_name ($3, 0); }
803 | maybe_self_path super_path identifier_path_for_expr
804 { $$ = super_name ($3, $2); }
805 | COLONCOLON identifier_path_for_expr
806 { $$ = crate_name ($2); }
807 | KW_EXTERN identifier_path_for_expr
809 /* This is a gdb extension to make it possible to
810 refer to items in other crates. It just bypasses
811 adding the current crate to the front of the
813 $$ = ast_path (rust_concat3 ("::", $2->left.sval.ptr, NULL),
818 identifier_path_for_expr:
820 { $$ = ast_path ($1, NULL); }
821 | identifier_path_for_expr COLONCOLON IDENT
823 $$ = ast_path (rust_concat3 ($1->left.sval.ptr, "::",
827 | identifier_path_for_expr COLONCOLON '<' type_list '>'
828 { $$ = ast_path ($1->left.sval, $4); }
829 | identifier_path_for_expr COLONCOLON '<' type_list RSH
831 $$ = ast_path ($1->left.sval, $4);
832 rust_push_back ('>');
837 identifier_path_for_type
838 | KW_SELF COLONCOLON identifier_path_for_type
839 { $$ = super_name ($3, 0); }
840 | maybe_self_path super_path identifier_path_for_type
841 { $$ = super_name ($3, $2); }
842 | COLONCOLON identifier_path_for_type
843 { $$ = crate_name ($2); }
844 | KW_EXTERN identifier_path_for_type
846 /* This is a gdb extension to make it possible to
847 refer to items in other crates. It just bypasses
848 adding the current crate to the front of the
850 $$ = ast_path (rust_concat3 ("::", $2->left.sval.ptr, NULL),
855 just_identifiers_for_type:
857 { $$ = ast_path ($1, NULL); }
858 | just_identifiers_for_type COLONCOLON IDENT
860 $$ = ast_path (rust_concat3 ($1->left.sval.ptr, "::",
866 identifier_path_for_type:
867 just_identifiers_for_type
868 | just_identifiers_for_type '<' type_list '>'
869 { $$ = ast_path ($1->left.sval, $3); }
870 | just_identifiers_for_type '<' type_list RSH
872 $$ = ast_path ($1->left.sval, $3);
873 rust_push_back ('>');
879 | '[' type ';' INTEGER ']'
880 { $$ = ast_array_type ($2, $4); }
881 | '[' type ';' DECIMAL_INTEGER ']'
882 { $$ = ast_array_type ($2, $4); }
884 { $$ = ast_slice_type ($3); }
886 { $$ = ast_reference_type ($2); }
888 { $$ = ast_pointer_type ($3, 1); }
890 { $$ = ast_pointer_type ($3, 0); }
891 | KW_FN '(' maybe_type_list ')' ARROW type
892 { $$ = ast_function_type ($6, $3); }
893 | '(' maybe_type_list ')'
894 { $$ = ast_tuple_type ($2); }
907 rust_op_vector *result = current_parser->new_op_vector ();
908 result->push_back ($1);
920 /* A struct of this type is used to describe a token. */
926 enum exp_opcode opcode;
929 /* Identifier tokens. */
931 static const struct token_info identifier_tokens[] =
933 { "as", KW_AS, OP_NULL },
934 { "false", KW_FALSE, OP_NULL },
935 { "if", 0, OP_NULL },
936 { "mut", KW_MUT, OP_NULL },
937 { "const", KW_CONST, OP_NULL },
938 { "self", KW_SELF, OP_NULL },
939 { "super", KW_SUPER, OP_NULL },
940 { "true", KW_TRUE, OP_NULL },
941 { "extern", KW_EXTERN, OP_NULL },
942 { "fn", KW_FN, OP_NULL },
943 { "sizeof", KW_SIZEOF, OP_NULL },
946 /* Operator tokens, sorted longest first. */
948 static const struct token_info operator_tokens[] =
950 { ">>=", COMPOUND_ASSIGN, BINOP_RSH },
951 { "<<=", COMPOUND_ASSIGN, BINOP_LSH },
953 { "<<", LSH, OP_NULL },
954 { ">>", RSH, OP_NULL },
955 { "&&", ANDAND, OP_NULL },
956 { "||", OROR, OP_NULL },
957 { "==", EQEQ, OP_NULL },
958 { "!=", NOTEQ, OP_NULL },
959 { "<=", LTEQ, OP_NULL },
960 { ">=", GTEQ, OP_NULL },
961 { "+=", COMPOUND_ASSIGN, BINOP_ADD },
962 { "-=", COMPOUND_ASSIGN, BINOP_SUB },
963 { "*=", COMPOUND_ASSIGN, BINOP_MUL },
964 { "/=", COMPOUND_ASSIGN, BINOP_DIV },
965 { "%=", COMPOUND_ASSIGN, BINOP_REM },
966 { "&=", COMPOUND_ASSIGN, BINOP_BITWISE_AND },
967 { "|=", COMPOUND_ASSIGN, BINOP_BITWISE_IOR },
968 { "^=", COMPOUND_ASSIGN, BINOP_BITWISE_XOR },
969 { "..=", DOTDOTEQ, OP_NULL },
971 { "::", COLONCOLON, OP_NULL },
972 { "..", DOTDOT, OP_NULL },
973 { "->", ARROW, OP_NULL }
976 /* Helper function to copy to the name obstack. */
979 rust_copy_name (const char *name, int len)
981 return (const char *) obstack_copy0 (work_obstack, name, len);
984 /* Helper function to make an stoken from a C string. */
987 make_stoken (const char *p)
989 struct stoken result;
992 result.length = strlen (result.ptr);
996 /* Helper function to concatenate three strings on the name
1000 rust_concat3 (const char *s1, const char *s2, const char *s3)
1002 return make_stoken (obconcat (work_obstack, s1, s2, s3, (char *) NULL));
1005 /* Return an AST node referring to NAME, but relative to the crate's
1008 static const struct rust_op *
1009 crate_name (const struct rust_op *name)
1011 std::string crate = rust_crate_for_block (expression_context_block);
1012 struct stoken result;
1014 gdb_assert (name->opcode == OP_VAR_VALUE);
1017 error (_("Could not find crate for current location"));
1018 result = make_stoken (obconcat (work_obstack, "::", crate.c_str (), "::",
1019 name->left.sval.ptr, (char *) NULL));
1021 return ast_path (result, name->right.params);
1024 /* Create an AST node referring to a "super::" qualified name. IDENT
1025 is the base name and N_SUPERS is how many "super::"s were
1026 provided. N_SUPERS can be zero. */
1028 static const struct rust_op *
1029 super_name (const struct rust_op *ident, unsigned int n_supers)
1031 const char *scope = block_scope (expression_context_block);
1034 gdb_assert (ident->opcode == OP_VAR_VALUE);
1036 if (scope[0] == '\0')
1037 error (_("Couldn't find namespace scope for self::"));
1042 std::vector<int> offsets;
1043 unsigned int current_len;
1045 current_len = cp_find_first_component (scope);
1046 while (scope[current_len] != '\0')
1048 offsets.push_back (current_len);
1049 gdb_assert (scope[current_len] == ':');
1052 current_len += cp_find_first_component (scope
1056 len = offsets.size ();
1057 if (n_supers >= len)
1058 error (_("Too many super:: uses from '%s'"), scope);
1060 offset = offsets[len - n_supers];
1063 offset = strlen (scope);
1065 obstack_grow (work_obstack, "::", 2);
1066 obstack_grow (work_obstack, scope, offset);
1067 obstack_grow (work_obstack, "::", 2);
1068 obstack_grow0 (work_obstack, ident->left.sval.ptr, ident->left.sval.length);
1070 return ast_path (make_stoken ((const char *) obstack_finish (work_obstack)),
1071 ident->right.params);
1074 /* A helper that updates the innermost block as appropriate. */
1077 update_innermost_block (struct block_symbol sym)
1079 if (symbol_read_needs_frame (sym.symbol))
1080 innermost_block.update (sym);
1083 /* A helper to look up a Rust type, or fail. This only works for
1084 types defined by rust_language_arch_info. */
1086 static struct type *
1087 rust_type (const char *name)
1091 type = language_lookup_primitive_type (current_parser->language (),
1092 current_parser->arch (),
1095 error (_("Could not find Rust type %s"), name);
1099 /* Lex a hex number with at least MIN digits and at most MAX
1103 lex_hex (int min, int max)
1105 uint32_t result = 0;
1107 /* We only want to stop at MAX if we're lexing a byte escape. */
1108 int check_max = min == max;
1110 while ((check_max ? len <= max : 1)
1111 && ((lexptr[0] >= 'a' && lexptr[0] <= 'f')
1112 || (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1113 || (lexptr[0] >= '0' && lexptr[0] <= '9')))
1116 if (lexptr[0] >= 'a' && lexptr[0] <= 'f')
1117 result = result + 10 + lexptr[0] - 'a';
1118 else if (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1119 result = result + 10 + lexptr[0] - 'A';
1121 result = result + lexptr[0] - '0';
1127 error (_("Not enough hex digits seen"));
1130 gdb_assert (min != max);
1131 error (_("Overlong hex escape"));
1137 /* Lex an escape. IS_BYTE is true if we're lexing a byte escape;
1138 otherwise we're lexing a character escape. */
1141 lex_escape (int is_byte)
1145 gdb_assert (lexptr[0] == '\\');
1151 result = lex_hex (2, 2);
1156 error (_("Unicode escape in byte literal"));
1158 if (lexptr[0] != '{')
1159 error (_("Missing '{' in Unicode escape"));
1161 result = lex_hex (1, 6);
1162 /* Could do range checks here. */
1163 if (lexptr[0] != '}')
1164 error (_("Missing '}' in Unicode escape"));
1198 error (_("Invalid escape \\%c in literal"), lexptr[0]);
1204 /* Lex a character constant. */
1207 lex_character (void)
1212 if (lexptr[0] == 'b')
1217 gdb_assert (lexptr[0] == '\'');
1219 /* This should handle UTF-8 here. */
1220 if (lexptr[0] == '\\')
1221 value = lex_escape (is_byte);
1224 value = lexptr[0] & 0xff;
1228 if (lexptr[0] != '\'')
1229 error (_("Unterminated character literal"));
1232 rustyylval.typed_val_int.val = value;
1233 rustyylval.typed_val_int.type = rust_type (is_byte ? "u8" : "char");
1238 /* Return the offset of the double quote if STR looks like the start
1239 of a raw string, or 0 if STR does not start a raw string. */
1242 starts_raw_string (const char *str)
1244 const char *save = str;
1249 while (str[0] == '#')
1256 /* Return true if STR looks like the end of a raw string that had N
1257 hashes at the start. */
1260 ends_raw_string (const char *str, int n)
1264 gdb_assert (str[0] == '"');
1265 for (i = 0; i < n; ++i)
1266 if (str[i + 1] != '#')
1271 /* Lex a string constant. */
1276 int is_byte = lexptr[0] == 'b';
1281 raw_length = starts_raw_string (lexptr);
1282 lexptr += raw_length;
1283 gdb_assert (lexptr[0] == '"');
1292 if (lexptr[0] == '"' && ends_raw_string (lexptr, raw_length - 1))
1294 /* Exit with lexptr pointing after the final "#". */
1295 lexptr += raw_length;
1298 else if (lexptr[0] == '\0')
1299 error (_("Unexpected EOF in string"));
1301 value = lexptr[0] & 0xff;
1302 if (is_byte && value > 127)
1303 error (_("Non-ASCII value in raw byte string"));
1304 obstack_1grow (work_obstack, value);
1308 else if (lexptr[0] == '"')
1310 /* Make sure to skip the quote. */
1314 else if (lexptr[0] == '\\')
1316 value = lex_escape (is_byte);
1319 obstack_1grow (work_obstack, value);
1321 convert_between_encodings ("UTF-32", "UTF-8", (gdb_byte *) &value,
1322 sizeof (value), sizeof (value),
1323 work_obstack, translit_none);
1325 else if (lexptr[0] == '\0')
1326 error (_("Unexpected EOF in string"));
1329 value = lexptr[0] & 0xff;
1330 if (is_byte && value > 127)
1331 error (_("Non-ASCII value in byte string"));
1332 obstack_1grow (work_obstack, value);
1337 rustyylval.sval.length = obstack_object_size (work_obstack);
1338 rustyylval.sval.ptr = (const char *) obstack_finish (work_obstack);
1339 return is_byte ? BYTESTRING : STRING;
1342 /* Return true if STRING starts with whitespace followed by a digit. */
1345 space_then_number (const char *string)
1347 const char *p = string;
1349 while (p[0] == ' ' || p[0] == '\t')
1354 return *p >= '0' && *p <= '9';
1357 /* Return true if C can start an identifier. */
1360 rust_identifier_start_p (char c)
1362 return ((c >= 'a' && c <= 'z')
1363 || (c >= 'A' && c <= 'Z')
1368 /* Lex an identifier. */
1371 lex_identifier (void)
1373 const char *start = lexptr;
1374 unsigned int length;
1375 const struct token_info *token;
1377 int is_gdb_var = lexptr[0] == '$';
1379 gdb_assert (rust_identifier_start_p (lexptr[0]));
1383 /* For the time being this doesn't handle Unicode rules. Non-ASCII
1384 identifiers are gated anyway. */
1385 while ((lexptr[0] >= 'a' && lexptr[0] <= 'z')
1386 || (lexptr[0] >= 'A' && lexptr[0] <= 'Z')
1388 || (is_gdb_var && lexptr[0] == '$')
1389 || (lexptr[0] >= '0' && lexptr[0] <= '9'))
1393 length = lexptr - start;
1395 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
1397 if (length == strlen (identifier_tokens[i].name)
1398 && strncmp (identifier_tokens[i].name, start, length) == 0)
1400 token = &identifier_tokens[i];
1407 if (token->value == 0)
1409 /* Leave the terminating token alone. */
1414 else if (token == NULL
1415 && (strncmp (start, "thread", length) == 0
1416 || strncmp (start, "task", length) == 0)
1417 && space_then_number (lexptr))
1419 /* "task" or "thread" followed by a number terminates the
1420 parse, per gdb rules. */
1425 if (token == NULL || (parse_completion && lexptr[0] == '\0'))
1426 rustyylval.sval = make_stoken (rust_copy_name (start, length));
1428 if (parse_completion && lexptr[0] == '\0')
1430 /* Prevent rustyylex from returning two COMPLETE tokens. */
1431 prev_lexptr = lexptr;
1436 return token->value;
1442 /* Lex an operator. */
1447 const struct token_info *token = NULL;
1450 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
1452 if (strncmp (operator_tokens[i].name, lexptr,
1453 strlen (operator_tokens[i].name)) == 0)
1455 lexptr += strlen (operator_tokens[i].name);
1456 token = &operator_tokens[i];
1463 rustyylval.opcode = token->opcode;
1464 return token->value;
1475 regmatch_t subexps[NUM_SUBEXPRESSIONS];
1478 int could_be_decimal = 1;
1479 int implicit_i32 = 0;
1480 const char *type_name = NULL;
1483 int type_index = -1;
1486 match = regexec (&number_regex, lexptr, ARRAY_SIZE (subexps), subexps, 0);
1487 /* Failure means the regexp is broken. */
1488 gdb_assert (match == 0);
1490 if (subexps[INT_TEXT].rm_so != -1)
1492 /* Integer part matched. */
1494 end_index = subexps[INT_TEXT].rm_eo;
1495 if (subexps[INT_TYPE].rm_so == -1)
1502 type_index = INT_TYPE;
1503 could_be_decimal = 0;
1506 else if (subexps[FLOAT_TYPE1].rm_so != -1)
1508 /* Found floating point type suffix. */
1509 end_index = subexps[FLOAT_TYPE1].rm_so;
1510 type_index = FLOAT_TYPE1;
1512 else if (subexps[FLOAT_TYPE2].rm_so != -1)
1514 /* Found floating point type suffix. */
1515 end_index = subexps[FLOAT_TYPE2].rm_so;
1516 type_index = FLOAT_TYPE2;
1520 /* Any other floating point match. */
1521 end_index = subexps[0].rm_eo;
1525 /* We need a special case if the final character is ".". In this
1526 case we might need to parse an integer. For example, "23.f()" is
1527 a request for a trait method call, not a syntax error involving
1528 the floating point number "23.". */
1529 gdb_assert (subexps[0].rm_eo > 0);
1530 if (lexptr[subexps[0].rm_eo - 1] == '.')
1532 const char *next = skip_spaces (&lexptr[subexps[0].rm_eo]);
1534 if (rust_identifier_start_p (*next) || *next == '.')
1538 end_index = subexps[0].rm_eo;
1540 could_be_decimal = 1;
1545 /* Compute the type name if we haven't already. */
1546 std::string type_name_holder;
1547 if (type_name == NULL)
1549 gdb_assert (type_index != -1);
1550 type_name_holder = std::string (lexptr + subexps[type_index].rm_so,
1551 (subexps[type_index].rm_eo
1552 - subexps[type_index].rm_so));
1553 type_name = type_name_holder.c_str ();
1556 /* Look up the type. */
1557 type = rust_type (type_name);
1559 /* Copy the text of the number and remove the "_"s. */
1561 for (i = 0; i < end_index && lexptr[i]; ++i)
1563 if (lexptr[i] == '_')
1564 could_be_decimal = 0;
1566 number.push_back (lexptr[i]);
1569 /* Advance past the match. */
1570 lexptr += subexps[0].rm_eo;
1572 /* Parse the number. */
1579 if (number[0] == '0')
1581 if (number[1] == 'x')
1583 else if (number[1] == 'o')
1585 else if (number[1] == 'b')
1590 could_be_decimal = 0;
1594 value = strtoul (number.c_str () + offset, NULL, radix);
1595 if (implicit_i32 && value >= ((uint64_t) 1) << 31)
1596 type = rust_type ("i64");
1598 rustyylval.typed_val_int.val = value;
1599 rustyylval.typed_val_int.type = type;
1603 rustyylval.typed_val_float.type = type;
1604 bool parsed = parse_float (number.c_str (), number.length (),
1605 rustyylval.typed_val_float.type,
1606 rustyylval.typed_val_float.val);
1607 gdb_assert (parsed);
1610 return is_integer ? (could_be_decimal ? DECIMAL_INTEGER : INTEGER) : FLOAT;
1618 /* Skip all leading whitespace. */
1619 while (lexptr[0] == ' ' || lexptr[0] == '\t' || lexptr[0] == '\r'
1620 || lexptr[0] == '\n')
1623 /* If we hit EOF and we're completing, then return COMPLETE -- maybe
1624 we're completing an empty string at the end of a field_expr.
1625 But, we don't want to return two COMPLETE tokens in a row. */
1626 if (lexptr[0] == '\0' && lexptr == prev_lexptr)
1628 prev_lexptr = lexptr;
1629 if (lexptr[0] == '\0')
1631 if (parse_completion)
1633 rustyylval.sval = make_stoken ("");
1639 if (lexptr[0] >= '0' && lexptr[0] <= '9')
1640 return lex_number ();
1641 else if (lexptr[0] == 'b' && lexptr[1] == '\'')
1642 return lex_character ();
1643 else if (lexptr[0] == 'b' && lexptr[1] == '"')
1644 return lex_string ();
1645 else if (lexptr[0] == 'b' && starts_raw_string (lexptr + 1))
1646 return lex_string ();
1647 else if (starts_raw_string (lexptr))
1648 return lex_string ();
1649 else if (rust_identifier_start_p (lexptr[0]))
1650 return lex_identifier ();
1651 else if (lexptr[0] == '"')
1652 return lex_string ();
1653 else if (lexptr[0] == '\'')
1654 return lex_character ();
1655 else if (lexptr[0] == '}' || lexptr[0] == ']')
1657 /* Falls through to lex_operator. */
1660 else if (lexptr[0] == '(' || lexptr[0] == '{')
1662 /* Falls through to lex_operator. */
1665 else if (lexptr[0] == ',' && comma_terminates && paren_depth == 0)
1668 return lex_operator ();
1671 /* Push back a single character to be re-lexed. */
1674 rust_push_back (char c)
1676 /* Can't be called before any lexing. */
1677 gdb_assert (prev_lexptr != NULL);
1680 gdb_assert (*lexptr == c);
1685 /* Make an arbitrary operation and fill in the fields. */
1687 static const struct rust_op *
1688 ast_operation (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->left.op = left;
1695 result->right.op = right;
1700 /* Make a compound assignment operation. */
1702 static const struct rust_op *
1703 ast_compound_assignment (enum exp_opcode opcode, const struct rust_op *left,
1704 const struct rust_op *right)
1706 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1708 result->opcode = opcode;
1709 result->compound_assignment = 1;
1710 result->left.op = left;
1711 result->right.op = right;
1716 /* Make a typed integer literal operation. */
1718 static const struct rust_op *
1719 ast_literal (struct typed_val_int val)
1721 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1723 result->opcode = OP_LONG;
1724 result->left.typed_val_int = val;
1729 /* Make a typed floating point literal operation. */
1731 static const struct rust_op *
1732 ast_dliteral (struct typed_val_float val)
1734 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1736 result->opcode = OP_FLOAT;
1737 result->left.typed_val_float = val;
1742 /* Make a unary operation. */
1744 static const struct rust_op *
1745 ast_unary (enum exp_opcode opcode, const struct rust_op *expr)
1747 return ast_operation (opcode, expr, NULL);
1750 /* Make a cast operation. */
1752 static const struct rust_op *
1753 ast_cast (const struct rust_op *expr, const struct rust_op *type)
1755 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1757 result->opcode = UNOP_CAST;
1758 result->left.op = expr;
1759 result->right.op = type;
1764 /* Make a call-like operation. This is nominally a function call, but
1765 when lowering we may discover that it actually represents the
1766 creation of a tuple struct. */
1768 static const struct rust_op *
1769 ast_call_ish (enum exp_opcode opcode, const struct rust_op *expr,
1770 rust_op_vector *params)
1772 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1774 result->opcode = opcode;
1775 result->left.op = expr;
1776 result->right.params = params;
1781 /* Make a structure creation operation. */
1783 static const struct rust_op *
1784 ast_struct (const struct rust_op *name, rust_set_vector *fields)
1786 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1788 result->opcode = OP_AGGREGATE;
1789 result->left.op = name;
1790 result->right.field_inits = fields;
1795 /* Make an identifier path. */
1797 static const struct rust_op *
1798 ast_path (struct stoken path, rust_op_vector *params)
1800 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1802 result->opcode = OP_VAR_VALUE;
1803 result->left.sval = path;
1804 result->right.params = params;
1809 /* Make a string constant operation. */
1811 static const struct rust_op *
1812 ast_string (struct stoken str)
1814 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1816 result->opcode = OP_STRING;
1817 result->left.sval = str;
1822 /* Make a field expression. */
1824 static const struct rust_op *
1825 ast_structop (const struct rust_op *left, const char *name, int completing)
1827 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1829 result->opcode = STRUCTOP_STRUCT;
1830 result->completing = completing;
1831 result->left.op = left;
1832 result->right.sval = make_stoken (name);
1837 /* Make an anonymous struct operation, like 'x.0'. */
1839 static const struct rust_op *
1840 ast_structop_anonymous (const struct rust_op *left,
1841 struct typed_val_int number)
1843 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1845 result->opcode = STRUCTOP_ANONYMOUS;
1846 result->left.op = left;
1847 result->right.typed_val_int = number;
1852 /* Make a range operation. */
1854 static const struct rust_op *
1855 ast_range (const struct rust_op *lhs, const struct rust_op *rhs,
1858 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1860 result->opcode = OP_RANGE;
1861 result->inclusive = inclusive;
1862 result->left.op = lhs;
1863 result->right.op = rhs;
1868 /* A helper function to make a type-related AST node. */
1870 static struct rust_op *
1871 ast_basic_type (enum type_code typecode)
1873 struct rust_op *result = OBSTACK_ZALLOC (work_obstack, struct rust_op);
1875 result->opcode = OP_TYPE;
1876 result->typecode = typecode;
1880 /* Create an AST node describing an array type. */
1882 static const struct rust_op *
1883 ast_array_type (const struct rust_op *lhs, struct typed_val_int val)
1885 struct rust_op *result = ast_basic_type (TYPE_CODE_ARRAY);
1887 result->left.op = lhs;
1888 result->right.typed_val_int = val;
1892 /* Create an AST node describing a reference type. */
1894 static const struct rust_op *
1895 ast_slice_type (const struct rust_op *type)
1897 /* Use TYPE_CODE_COMPLEX just because it is handy. */
1898 struct rust_op *result = ast_basic_type (TYPE_CODE_COMPLEX);
1900 result->left.op = type;
1904 /* Create an AST node describing a reference type. */
1906 static const struct rust_op *
1907 ast_reference_type (const struct rust_op *type)
1909 struct rust_op *result = ast_basic_type (TYPE_CODE_REF);
1911 result->left.op = type;
1915 /* Create an AST node describing a pointer type. */
1917 static const struct rust_op *
1918 ast_pointer_type (const struct rust_op *type, int is_mut)
1920 struct rust_op *result = ast_basic_type (TYPE_CODE_PTR);
1922 result->left.op = type;
1923 /* For the time being we ignore is_mut. */
1927 /* Create an AST node describing a function type. */
1929 static const struct rust_op *
1930 ast_function_type (const struct rust_op *rtype, rust_op_vector *params)
1932 struct rust_op *result = ast_basic_type (TYPE_CODE_FUNC);
1934 result->left.op = rtype;
1935 result->right.params = params;
1939 /* Create an AST node describing a tuple type. */
1941 static const struct rust_op *
1942 ast_tuple_type (rust_op_vector *params)
1944 struct rust_op *result = ast_basic_type (TYPE_CODE_STRUCT);
1946 result->left.params = params;
1950 /* A helper to appropriately munge NAME and BLOCK depending on the
1951 presence of a leading "::". */
1954 munge_name_and_block (const char **name, const struct block **block)
1956 /* If it is a global reference, skip the current block in favor of
1957 the static block. */
1958 if (strncmp (*name, "::", 2) == 0)
1961 *block = block_static_block (*block);
1965 /* Like lookup_symbol, but handles Rust namespace conventions, and
1966 doesn't require field_of_this_result. */
1968 static struct block_symbol
1969 rust_lookup_symbol (const char *name, const struct block *block,
1970 const domain_enum domain)
1972 struct block_symbol result;
1974 munge_name_and_block (&name, &block);
1976 result = lookup_symbol (name, block, domain, NULL);
1977 if (result.symbol != NULL)
1978 update_innermost_block (result);
1982 /* Look up a type, following Rust namespace conventions. */
1984 static struct type *
1985 rust_lookup_type (const char *name, const struct block *block)
1987 struct block_symbol result;
1990 munge_name_and_block (&name, &block);
1992 result = lookup_symbol (name, block, STRUCT_DOMAIN, NULL);
1993 if (result.symbol != NULL)
1995 update_innermost_block (result);
1996 return SYMBOL_TYPE (result.symbol);
1999 type = lookup_typename (current_parser->language (), current_parser->arch (),
2004 /* Last chance, try a built-in type. */
2005 return language_lookup_primitive_type (current_parser->language (),
2006 current_parser->arch (),
2010 static struct type *convert_ast_to_type (struct parser_state *state,
2011 const struct rust_op *operation);
2012 static const char *convert_name (struct parser_state *state,
2013 const struct rust_op *operation);
2015 /* Convert a vector of rust_ops representing types to a vector of
2018 static std::vector<struct type *>
2019 convert_params_to_types (struct parser_state *state, rust_op_vector *params)
2021 std::vector<struct type *> result;
2023 if (params != nullptr)
2025 for (const rust_op *op : *params)
2026 result.push_back (convert_ast_to_type (state, op));
2032 /* Convert a rust_op representing a type to a struct type *. */
2034 static struct type *
2035 convert_ast_to_type (struct parser_state *state,
2036 const struct rust_op *operation)
2038 struct type *type, *result = NULL;
2040 if (operation->opcode == OP_VAR_VALUE)
2042 const char *varname = convert_name (state, operation);
2044 result = rust_lookup_type (varname, expression_context_block);
2046 error (_("No typed name '%s' in current context"), varname);
2050 gdb_assert (operation->opcode == OP_TYPE);
2052 switch (operation->typecode)
2054 case TYPE_CODE_ARRAY:
2055 type = convert_ast_to_type (state, operation->left.op);
2056 if (operation->right.typed_val_int.val < 0)
2057 error (_("Negative array length"));
2058 result = lookup_array_range_type (type, 0,
2059 operation->right.typed_val_int.val - 1);
2062 case TYPE_CODE_COMPLEX:
2064 struct type *usize = rust_type ("usize");
2066 type = convert_ast_to_type (state, operation->left.op);
2067 result = rust_slice_type ("&[*gdb*]", type, usize);
2073 /* For now we treat &x and *x identically. */
2074 type = convert_ast_to_type (state, operation->left.op);
2075 result = lookup_pointer_type (type);
2078 case TYPE_CODE_FUNC:
2080 std::vector<struct type *> args
2081 (convert_params_to_types (state, operation->right.params));
2082 struct type **argtypes = NULL;
2084 type = convert_ast_to_type (state, operation->left.op);
2086 argtypes = args.data ();
2089 = lookup_function_type_with_arguments (type, args.size (),
2091 result = lookup_pointer_type (result);
2095 case TYPE_CODE_STRUCT:
2097 std::vector<struct type *> args
2098 (convert_params_to_types (state, operation->left.params));
2102 obstack_1grow (work_obstack, '(');
2103 for (i = 0; i < args.size (); ++i)
2105 std::string type_name = type_to_string (args[i]);
2108 obstack_1grow (work_obstack, ',');
2109 obstack_grow_str (work_obstack, type_name.c_str ());
2112 obstack_grow_str0 (work_obstack, ")");
2113 name = (const char *) obstack_finish (work_obstack);
2115 /* We don't allow creating new tuple types (yet), but we do
2116 allow looking up existing tuple types. */
2117 result = rust_lookup_type (name, expression_context_block);
2119 error (_("could not find tuple type '%s'"), name);
2124 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_type");
2127 gdb_assert (result != NULL);
2131 /* A helper function to turn a rust_op representing a name into a full
2132 name. This applies generic arguments as needed. The returned name
2133 is allocated on the work obstack. */
2136 convert_name (struct parser_state *state, const struct rust_op *operation)
2140 gdb_assert (operation->opcode == OP_VAR_VALUE);
2142 if (operation->right.params == NULL)
2143 return operation->left.sval.ptr;
2145 std::vector<struct type *> types
2146 (convert_params_to_types (state, operation->right.params));
2148 obstack_grow_str (work_obstack, operation->left.sval.ptr);
2149 obstack_1grow (work_obstack, '<');
2150 for (i = 0; i < types.size (); ++i)
2152 std::string type_name = type_to_string (types[i]);
2155 obstack_1grow (work_obstack, ',');
2157 obstack_grow_str (work_obstack, type_name.c_str ());
2159 obstack_grow_str0 (work_obstack, ">");
2161 return (const char *) obstack_finish (work_obstack);
2164 static void convert_ast_to_expression (struct parser_state *state,
2165 const struct rust_op *operation,
2166 const struct rust_op *top,
2167 bool want_type = false);
2169 /* A helper function that converts a vec of rust_ops to a gdb
2173 convert_params_to_expression (struct parser_state *state,
2174 rust_op_vector *params,
2175 const struct rust_op *top)
2177 for (const rust_op *elem : *params)
2178 convert_ast_to_expression (state, elem, top);
2181 /* Lower a rust_op to a gdb expression. STATE is the parser state.
2182 OPERATION is the operation to lower. TOP is a pointer to the
2183 top-most operation; it is used to handle the special case where the
2184 top-most expression is an identifier and can be optionally lowered
2185 to OP_TYPE. WANT_TYPE is a flag indicating that, if the expression
2186 is the name of a type, then emit an OP_TYPE for it (rather than
2187 erroring). If WANT_TYPE is set, then the similar TOP handling is
2191 convert_ast_to_expression (struct parser_state *state,
2192 const struct rust_op *operation,
2193 const struct rust_op *top,
2196 switch (operation->opcode)
2199 write_exp_elt_opcode (state, OP_LONG);
2200 write_exp_elt_type (state, operation->left.typed_val_int.type);
2201 write_exp_elt_longcst (state, operation->left.typed_val_int.val);
2202 write_exp_elt_opcode (state, OP_LONG);
2206 write_exp_elt_opcode (state, OP_FLOAT);
2207 write_exp_elt_type (state, operation->left.typed_val_float.type);
2208 write_exp_elt_floatcst (state, operation->left.typed_val_float.val);
2209 write_exp_elt_opcode (state, OP_FLOAT);
2212 case STRUCTOP_STRUCT:
2214 convert_ast_to_expression (state, operation->left.op, top);
2216 if (operation->completing)
2217 mark_struct_expression (state);
2218 write_exp_elt_opcode (state, STRUCTOP_STRUCT);
2219 write_exp_string (state, operation->right.sval);
2220 write_exp_elt_opcode (state, STRUCTOP_STRUCT);
2224 case STRUCTOP_ANONYMOUS:
2226 convert_ast_to_expression (state, operation->left.op, top);
2228 write_exp_elt_opcode (state, STRUCTOP_ANONYMOUS);
2229 write_exp_elt_longcst (state, operation->right.typed_val_int.val);
2230 write_exp_elt_opcode (state, STRUCTOP_ANONYMOUS);
2235 convert_ast_to_expression (state, operation->left.op, top, true);
2236 write_exp_elt_opcode (state, UNOP_SIZEOF);
2241 case UNOP_COMPLEMENT:
2244 convert_ast_to_expression (state, operation->left.op, top);
2245 write_exp_elt_opcode (state, operation->opcode);
2248 case BINOP_SUBSCRIPT:
2255 case BINOP_BITWISE_AND:
2256 case BINOP_BITWISE_IOR:
2257 case BINOP_BITWISE_XOR:
2260 case BINOP_LOGICAL_OR:
2261 case BINOP_LOGICAL_AND:
2263 case BINOP_NOTEQUAL:
2270 convert_ast_to_expression (state, operation->left.op, top);
2271 convert_ast_to_expression (state, operation->right.op, top);
2272 if (operation->compound_assignment)
2274 write_exp_elt_opcode (state, BINOP_ASSIGN_MODIFY);
2275 write_exp_elt_opcode (state, operation->opcode);
2276 write_exp_elt_opcode (state, BINOP_ASSIGN_MODIFY);
2279 write_exp_elt_opcode (state, operation->opcode);
2281 if (operation->compound_assignment
2282 || operation->opcode == BINOP_ASSIGN)
2286 type = language_lookup_primitive_type (parse_language (state),
2287 parse_gdbarch (state),
2290 write_exp_elt_opcode (state, OP_LONG);
2291 write_exp_elt_type (state, type);
2292 write_exp_elt_longcst (state, 0);
2293 write_exp_elt_opcode (state, OP_LONG);
2295 write_exp_elt_opcode (state, BINOP_COMMA);
2301 struct type *type = convert_ast_to_type (state, operation->right.op);
2303 convert_ast_to_expression (state, operation->left.op, top);
2304 write_exp_elt_opcode (state, UNOP_CAST);
2305 write_exp_elt_type (state, type);
2306 write_exp_elt_opcode (state, UNOP_CAST);
2312 if (operation->left.op->opcode == OP_VAR_VALUE)
2315 const char *varname = convert_name (state, operation->left.op);
2317 type = rust_lookup_type (varname, expression_context_block);
2320 /* This is actually a tuple struct expression, not a
2322 rust_op_vector *params = operation->right.params;
2324 if (TYPE_CODE (type) != TYPE_CODE_NAMESPACE)
2326 if (!rust_tuple_struct_type_p (type))
2327 error (_("Type %s is not a tuple struct"), varname);
2329 for (int i = 0; i < params->size (); ++i)
2331 char *cell = get_print_cell ();
2333 xsnprintf (cell, PRINT_CELL_SIZE, "__%d", i);
2334 write_exp_elt_opcode (state, OP_NAME);
2335 write_exp_string (state, make_stoken (cell));
2336 write_exp_elt_opcode (state, OP_NAME);
2338 convert_ast_to_expression (state, (*params)[i], top);
2341 write_exp_elt_opcode (state, OP_AGGREGATE);
2342 write_exp_elt_type (state, type);
2343 write_exp_elt_longcst (state, 2 * params->size ());
2344 write_exp_elt_opcode (state, OP_AGGREGATE);
2349 convert_ast_to_expression (state, operation->left.op, top);
2350 convert_params_to_expression (state, operation->right.params, top);
2351 write_exp_elt_opcode (state, OP_FUNCALL);
2352 write_exp_elt_longcst (state, operation->right.params->size ());
2353 write_exp_elt_longcst (state, OP_FUNCALL);
2358 gdb_assert (operation->left.op == NULL);
2359 convert_params_to_expression (state, operation->right.params, top);
2360 write_exp_elt_opcode (state, OP_ARRAY);
2361 write_exp_elt_longcst (state, 0);
2362 write_exp_elt_longcst (state, operation->right.params->size () - 1);
2363 write_exp_elt_longcst (state, OP_ARRAY);
2368 struct block_symbol sym;
2369 const char *varname;
2371 if (operation->left.sval.ptr[0] == '$')
2373 write_dollar_variable (state, operation->left.sval);
2377 varname = convert_name (state, operation);
2378 sym = rust_lookup_symbol (varname, expression_context_block,
2380 if (sym.symbol != NULL && SYMBOL_CLASS (sym.symbol) != LOC_TYPEDEF)
2382 write_exp_elt_opcode (state, OP_VAR_VALUE);
2383 write_exp_elt_block (state, sym.block);
2384 write_exp_elt_sym (state, sym.symbol);
2385 write_exp_elt_opcode (state, OP_VAR_VALUE);
2389 struct type *type = NULL;
2391 if (sym.symbol != NULL)
2393 gdb_assert (SYMBOL_CLASS (sym.symbol) == LOC_TYPEDEF);
2394 type = SYMBOL_TYPE (sym.symbol);
2397 type = rust_lookup_type (varname, expression_context_block);
2399 error (_("No symbol '%s' in current context"), varname);
2402 && TYPE_CODE (type) == TYPE_CODE_STRUCT
2403 && TYPE_NFIELDS (type) == 0)
2405 /* A unit-like struct. */
2406 write_exp_elt_opcode (state, OP_AGGREGATE);
2407 write_exp_elt_type (state, type);
2408 write_exp_elt_longcst (state, 0);
2409 write_exp_elt_opcode (state, OP_AGGREGATE);
2411 else if (want_type || operation == top)
2413 write_exp_elt_opcode (state, OP_TYPE);
2414 write_exp_elt_type (state, type);
2415 write_exp_elt_opcode (state, OP_TYPE);
2418 error (_("Found type '%s', which can't be "
2419 "evaluated in this context"),
2428 rust_set_vector *fields = operation->right.field_inits;
2433 for (const set_field &init : *fields)
2435 if (init.name.ptr != NULL)
2437 write_exp_elt_opcode (state, OP_NAME);
2438 write_exp_string (state, init.name);
2439 write_exp_elt_opcode (state, OP_NAME);
2443 convert_ast_to_expression (state, init.init, top);
2446 if (init.name.ptr == NULL)
2448 /* This is handled differently from Ada in our
2450 write_exp_elt_opcode (state, OP_OTHERS);
2454 name = convert_name (state, operation->left.op);
2455 type = rust_lookup_type (name, expression_context_block);
2457 error (_("Could not find type '%s'"), operation->left.sval.ptr);
2459 if (TYPE_CODE (type) != TYPE_CODE_STRUCT
2460 || rust_tuple_type_p (type)
2461 || rust_tuple_struct_type_p (type))
2462 error (_("Struct expression applied to non-struct type"));
2464 write_exp_elt_opcode (state, OP_AGGREGATE);
2465 write_exp_elt_type (state, type);
2466 write_exp_elt_longcst (state, length);
2467 write_exp_elt_opcode (state, OP_AGGREGATE);
2473 write_exp_elt_opcode (state, OP_STRING);
2474 write_exp_string (state, operation->left.sval);
2475 write_exp_elt_opcode (state, OP_STRING);
2481 enum range_type kind = BOTH_BOUND_DEFAULT;
2483 if (operation->left.op != NULL)
2485 convert_ast_to_expression (state, operation->left.op, top);
2486 kind = HIGH_BOUND_DEFAULT;
2488 if (operation->right.op != NULL)
2490 convert_ast_to_expression (state, operation->right.op, top);
2491 if (kind == BOTH_BOUND_DEFAULT)
2492 kind = (operation->inclusive
2493 ? LOW_BOUND_DEFAULT : LOW_BOUND_DEFAULT_EXCLUSIVE);
2496 gdb_assert (kind == HIGH_BOUND_DEFAULT);
2497 kind = (operation->inclusive
2498 ? NONE_BOUND_DEFAULT : NONE_BOUND_DEFAULT_EXCLUSIVE);
2503 /* Nothing should make an inclusive range without an upper
2505 gdb_assert (!operation->inclusive);
2508 write_exp_elt_opcode (state, OP_RANGE);
2509 write_exp_elt_longcst (state, kind);
2510 write_exp_elt_opcode (state, OP_RANGE);
2515 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_expression");
2521 /* The parser as exposed to gdb. */
2524 rust_parse (struct parser_state *state)
2528 /* This sets various globals and also clears them on
2530 rust_parser parser (state);
2532 result = rustyyparse ();
2534 if (!result || (parse_completion && parser.rust_ast != NULL))
2535 convert_ast_to_expression (state, parser.rust_ast, parser.rust_ast);
2540 /* The parser error handler. */
2543 rustyyerror (const char *msg)
2545 const char *where = prev_lexptr ? prev_lexptr : lexptr;
2546 error (_("%s in expression, near `%s'."), msg, where);
2553 /* Initialize the lexer for testing. */
2556 rust_lex_test_init (const char *input)
2563 /* A test helper that lexes a string, expecting a single token. It
2564 returns the lexer data for this token. */
2567 rust_lex_test_one (const char *input, int expected)
2572 rust_lex_test_init (input);
2574 token = rustyylex ();
2575 SELF_CHECK (token == expected);
2576 result = rustyylval;
2580 token = rustyylex ();
2581 SELF_CHECK (token == 0);
2587 /* Test that INPUT lexes as the integer VALUE. */
2590 rust_lex_int_test (const char *input, int value, int kind)
2592 RUSTSTYPE result = rust_lex_test_one (input, kind);
2593 SELF_CHECK (result.typed_val_int.val == value);
2596 /* Test that INPUT throws an exception with text ERR. */
2599 rust_lex_exception_test (const char *input, const char *err)
2603 /* The "kind" doesn't matter. */
2604 rust_lex_test_one (input, DECIMAL_INTEGER);
2607 CATCH (except, RETURN_MASK_ERROR)
2609 SELF_CHECK (strcmp (except.message, err) == 0);
2614 /* Test that INPUT lexes as the identifier, string, or byte-string
2615 VALUE. KIND holds the expected token kind. */
2618 rust_lex_stringish_test (const char *input, const char *value, int kind)
2620 RUSTSTYPE result = rust_lex_test_one (input, kind);
2621 SELF_CHECK (result.sval.length == strlen (value));
2622 SELF_CHECK (strncmp (result.sval.ptr, value, result.sval.length) == 0);
2625 /* Helper to test that a string parses as a given token sequence. */
2628 rust_lex_test_sequence (const char *input, int len, const int expected[])
2635 for (i = 0; i < len; ++i)
2637 int token = rustyylex ();
2639 SELF_CHECK (token == expected[i]);
2643 /* Tests for an integer-parsing corner case. */
2646 rust_lex_test_trailing_dot (void)
2648 const int expected1[] = { DECIMAL_INTEGER, '.', IDENT, '(', ')', 0 };
2649 const int expected2[] = { INTEGER, '.', IDENT, '(', ')', 0 };
2650 const int expected3[] = { FLOAT, EQEQ, '(', ')', 0 };
2651 const int expected4[] = { DECIMAL_INTEGER, DOTDOT, DECIMAL_INTEGER, 0 };
2653 rust_lex_test_sequence ("23.g()", ARRAY_SIZE (expected1), expected1);
2654 rust_lex_test_sequence ("23_0.g()", ARRAY_SIZE (expected2), expected2);
2655 rust_lex_test_sequence ("23.==()", ARRAY_SIZE (expected3), expected3);
2656 rust_lex_test_sequence ("23..25", ARRAY_SIZE (expected4), expected4);
2659 /* Tests of completion. */
2662 rust_lex_test_completion (void)
2664 const int expected[] = { IDENT, '.', COMPLETE, 0 };
2666 parse_completion = 1;
2668 rust_lex_test_sequence ("something.wha", ARRAY_SIZE (expected), expected);
2669 rust_lex_test_sequence ("something.", ARRAY_SIZE (expected), expected);
2671 parse_completion = 0;
2674 /* Test pushback. */
2677 rust_lex_test_push_back (void)
2681 rust_lex_test_init (">>=");
2683 token = rustyylex ();
2684 SELF_CHECK (token == COMPOUND_ASSIGN);
2685 SELF_CHECK (rustyylval.opcode == BINOP_RSH);
2687 rust_push_back ('=');
2689 token = rustyylex ();
2690 SELF_CHECK (token == '=');
2692 token = rustyylex ();
2693 SELF_CHECK (token == 0);
2696 /* Unit test the lexer. */
2699 rust_lex_tests (void)
2703 auto_obstack test_obstack;
2704 scoped_restore obstack_holder = make_scoped_restore (&work_obstack,
2707 // Set up dummy "parser", so that rust_type works.
2708 struct parser_state ps (0, &rust_language_defn, target_gdbarch ());
2709 rust_parser parser (&ps);
2711 rust_lex_test_one ("", 0);
2712 rust_lex_test_one (" \t \n \r ", 0);
2713 rust_lex_test_one ("thread 23", 0);
2714 rust_lex_test_one ("task 23", 0);
2715 rust_lex_test_one ("th 104", 0);
2716 rust_lex_test_one ("ta 97", 0);
2718 rust_lex_int_test ("'z'", 'z', INTEGER);
2719 rust_lex_int_test ("'\\xff'", 0xff, INTEGER);
2720 rust_lex_int_test ("'\\u{1016f}'", 0x1016f, INTEGER);
2721 rust_lex_int_test ("b'z'", 'z', INTEGER);
2722 rust_lex_int_test ("b'\\xfe'", 0xfe, INTEGER);
2723 rust_lex_int_test ("b'\\xFE'", 0xfe, INTEGER);
2724 rust_lex_int_test ("b'\\xfE'", 0xfe, INTEGER);
2726 /* Test all escapes in both modes. */
2727 rust_lex_int_test ("'\\n'", '\n', INTEGER);
2728 rust_lex_int_test ("'\\r'", '\r', INTEGER);
2729 rust_lex_int_test ("'\\t'", '\t', INTEGER);
2730 rust_lex_int_test ("'\\\\'", '\\', INTEGER);
2731 rust_lex_int_test ("'\\0'", '\0', INTEGER);
2732 rust_lex_int_test ("'\\''", '\'', INTEGER);
2733 rust_lex_int_test ("'\\\"'", '"', INTEGER);
2735 rust_lex_int_test ("b'\\n'", '\n', INTEGER);
2736 rust_lex_int_test ("b'\\r'", '\r', INTEGER);
2737 rust_lex_int_test ("b'\\t'", '\t', INTEGER);
2738 rust_lex_int_test ("b'\\\\'", '\\', INTEGER);
2739 rust_lex_int_test ("b'\\0'", '\0', INTEGER);
2740 rust_lex_int_test ("b'\\''", '\'', INTEGER);
2741 rust_lex_int_test ("b'\\\"'", '"', INTEGER);
2743 rust_lex_exception_test ("'z", "Unterminated character literal");
2744 rust_lex_exception_test ("b'\\x0'", "Not enough hex digits seen");
2745 rust_lex_exception_test ("b'\\u{0}'", "Unicode escape in byte literal");
2746 rust_lex_exception_test ("'\\x0'", "Not enough hex digits seen");
2747 rust_lex_exception_test ("'\\u0'", "Missing '{' in Unicode escape");
2748 rust_lex_exception_test ("'\\u{0", "Missing '}' in Unicode escape");
2749 rust_lex_exception_test ("'\\u{0000007}", "Overlong hex escape");
2750 rust_lex_exception_test ("'\\u{}", "Not enough hex digits seen");
2751 rust_lex_exception_test ("'\\Q'", "Invalid escape \\Q in literal");
2752 rust_lex_exception_test ("b'\\Q'", "Invalid escape \\Q in literal");
2754 rust_lex_int_test ("23", 23, DECIMAL_INTEGER);
2755 rust_lex_int_test ("2_344__29", 234429, INTEGER);
2756 rust_lex_int_test ("0x1f", 0x1f, INTEGER);
2757 rust_lex_int_test ("23usize", 23, INTEGER);
2758 rust_lex_int_test ("23i32", 23, INTEGER);
2759 rust_lex_int_test ("0x1_f", 0x1f, INTEGER);
2760 rust_lex_int_test ("0b1_101011__", 0x6b, INTEGER);
2761 rust_lex_int_test ("0o001177i64", 639, INTEGER);
2763 rust_lex_test_trailing_dot ();
2765 rust_lex_test_one ("23.", FLOAT);
2766 rust_lex_test_one ("23.99f32", FLOAT);
2767 rust_lex_test_one ("23e7", FLOAT);
2768 rust_lex_test_one ("23E-7", FLOAT);
2769 rust_lex_test_one ("23e+7", FLOAT);
2770 rust_lex_test_one ("23.99e+7f64", FLOAT);
2771 rust_lex_test_one ("23.82f32", FLOAT);
2773 rust_lex_stringish_test ("hibob", "hibob", IDENT);
2774 rust_lex_stringish_test ("hibob__93", "hibob__93", IDENT);
2775 rust_lex_stringish_test ("thread", "thread", IDENT);
2777 rust_lex_stringish_test ("\"string\"", "string", STRING);
2778 rust_lex_stringish_test ("\"str\\ting\"", "str\ting", STRING);
2779 rust_lex_stringish_test ("\"str\\\"ing\"", "str\"ing", STRING);
2780 rust_lex_stringish_test ("r\"str\\ing\"", "str\\ing", STRING);
2781 rust_lex_stringish_test ("r#\"str\\ting\"#", "str\\ting", STRING);
2782 rust_lex_stringish_test ("r###\"str\\\"ing\"###", "str\\\"ing", STRING);
2784 rust_lex_stringish_test ("b\"string\"", "string", BYTESTRING);
2785 rust_lex_stringish_test ("b\"\x73tring\"", "string", BYTESTRING);
2786 rust_lex_stringish_test ("b\"str\\\"ing\"", "str\"ing", BYTESTRING);
2787 rust_lex_stringish_test ("br####\"\\x73tring\"####", "\\x73tring",
2790 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
2791 rust_lex_test_one (identifier_tokens[i].name, identifier_tokens[i].value);
2793 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
2794 rust_lex_test_one (operator_tokens[i].name, operator_tokens[i].value);
2796 rust_lex_test_completion ();
2797 rust_lex_test_push_back ();
2800 #endif /* GDB_SELF_TEST */
2803 _initialize_rust_exp (void)
2805 int code = regcomp (&number_regex, number_regex_text, REG_EXTENDED);
2806 /* If the regular expression was incorrect, it was a programming
2808 gdb_assert (code == 0);
2811 selftests::register_test ("rust-lex", rust_lex_tests);