1 /* Bison parser for Rust expressions, for GDB.
2 Copyright (C) 2016 Free Software Foundation, Inc.
4 This file is part of GDB.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 /* Removing the last conflict seems difficult. */
28 #include "cp-support.h"
29 #include "gdb_obstack.h"
30 #include "gdb_regex.h"
31 #include "rust-lang.h"
32 #include "parser-defs.h"
37 #define GDB_YY_REMAP_PREFIX rust
40 #define RUSTSTYPE YYSTYPE
42 extern initialize_file_ftype _initialize_rust_exp;
45 typedef const struct rust_op *rust_op_ptr;
46 DEF_VEC_P (rust_op_ptr);
48 /* A typed integer constant. */
56 /* A typed floating point constant. */
58 struct typed_val_float
64 /* An identifier and an expression. This is used to represent one
65 element of a struct initializer. */
70 const struct rust_op *init;
73 typedef struct set_field set_field;
75 DEF_VEC_O (set_field);
78 static int rustyylex (void);
79 static void rust_push_back (char c);
80 static const char *rust_copy_name (const char *, int);
81 static struct stoken rust_concat3 (const char *, const char *, const char *);
82 static struct stoken make_stoken (const char *);
83 static struct block_symbol rust_lookup_symbol (const char *name,
84 const struct block *block,
85 const domain_enum domain);
86 static struct type *rust_lookup_type (const char *name,
87 const struct block *block);
88 static struct type *rust_type (const char *name);
90 static const struct rust_op *crate_name (const struct rust_op *name);
91 static const struct rust_op *super_name (const struct rust_op *name,
92 unsigned int n_supers);
94 static const struct rust_op *ast_operation (enum exp_opcode opcode,
95 const struct rust_op *left,
96 const struct rust_op *right);
97 static const struct rust_op *ast_compound_assignment
98 (enum exp_opcode opcode, const struct rust_op *left,
99 const struct rust_op *rust_op);
100 static const struct rust_op *ast_literal (struct typed_val_int val);
101 static const struct rust_op *ast_dliteral (struct typed_val_float val);
102 static const struct rust_op *ast_structop (const struct rust_op *left,
105 static const struct rust_op *ast_structop_anonymous
106 (const struct rust_op *left, struct typed_val_int number);
107 static const struct rust_op *ast_unary (enum exp_opcode opcode,
108 const struct rust_op *expr);
109 static const struct rust_op *ast_cast (const struct rust_op *expr,
110 const struct rust_op *type);
111 static const struct rust_op *ast_call_ish (enum exp_opcode opcode,
112 const struct rust_op *expr,
113 VEC (rust_op_ptr) **params);
114 static const struct rust_op *ast_path (struct stoken name,
115 VEC (rust_op_ptr) **params);
116 static const struct rust_op *ast_string (struct stoken str);
117 static const struct rust_op *ast_struct (const struct rust_op *name,
118 VEC (set_field) **fields);
119 static const struct rust_op *ast_range (const struct rust_op *lhs,
120 const struct rust_op *rhs);
121 static const struct rust_op *ast_array_type (const struct rust_op *lhs,
122 struct typed_val_int val);
123 static const struct rust_op *ast_slice_type (const struct rust_op *type);
124 static const struct rust_op *ast_reference_type (const struct rust_op *type);
125 static const struct rust_op *ast_pointer_type (const struct rust_op *type,
127 static const struct rust_op *ast_function_type (const struct rust_op *result,
128 VEC (rust_op_ptr) **params);
129 static const struct rust_op *ast_tuple_type (VEC (rust_op_ptr) **params);
131 /* The state of the parser, used internally when we are parsing the
134 static struct parser_state *pstate = NULL;
136 /* A regular expression for matching Rust numbers. This is split up
137 since it is very long and this gives us a way to comment the
140 static const char *number_regex_text =
141 /* subexpression 1: allows use of alternation, otherwise uninteresting */
143 /* First comes floating point. */
144 /* Recognize number after the decimal point, with optional
145 exponent and optional type suffix.
146 subexpression 2: allows "?", otherwise uninteresting
147 subexpression 3: if present, type suffix
149 "[0-9][0-9_]*\\.[0-9][0-9_]*([eE][-+]?[0-9][0-9_]*)?(f32|f64)?"
150 #define FLOAT_TYPE1 3
152 /* Recognize exponent without decimal point, with optional type
154 subexpression 4: if present, type suffix
156 #define FLOAT_TYPE2 4
157 "[0-9][0-9_]*[eE][-+]?[0-9][0-9_]*(f32|f64)?"
159 /* "23." is a valid floating point number, but "23.e5" and
160 "23.f32" are not. So, handle the trailing-. case
164 /* Finally come integers.
165 subexpression 5: text of integer
166 subexpression 6: if present, type suffix
167 subexpression 7: allows use of alternation, otherwise uninteresting
171 "(0x[a-fA-F0-9_]+|0o[0-7_]+|0b[01_]+|[0-9][0-9_]*)"
172 "([iu](size|8|16|32|64))?"
174 /* The number of subexpressions to allocate space for, including the
175 "0th" whole match subexpression. */
176 #define NUM_SUBEXPRESSIONS 8
178 /* The compiled number-matching regex. */
180 static regex_t number_regex;
182 /* True if we're running unit tests. */
184 static int unit_testing;
186 /* Obstack for data temporarily allocated during parsing. */
188 static struct obstack work_obstack;
190 /* Result of parsing. Points into work_obstack. */
192 static const struct rust_op *rust_ast;
198 /* A typed integer constant. */
199 struct typed_val_int typed_val_int;
201 /* A typed floating point constant. */
202 struct typed_val_float typed_val_float;
204 /* An identifier or string. */
207 /* A token representing an opcode, like "==". */
208 enum exp_opcode opcode;
210 /* A list of expressions; for example, the arguments to a function
212 VEC (rust_op_ptr) **params;
214 /* A list of field initializers. */
215 VEC (set_field) **field_inits;
217 /* A single field initializer. */
218 struct set_field one_field_init;
221 const struct rust_op *op;
223 /* A plain integer, for example used to count the number of
224 "super::" prefixes on a path. */
230 /* Rust AST operations. We build a tree of these; then lower them
231 to gdb expressions when parsing has completed. */
236 enum exp_opcode opcode;
237 /* If OPCODE is OP_TYPE, then this holds information about what type
238 is described by this node. */
239 enum type_code typecode;
240 /* Indicates whether OPCODE actually represents a compound
241 assignment. For example, if OPCODE is GTGT and this is false,
242 then this rust_op represents an ordinary ">>"; but if this is
243 true, then this rust_op represents ">>=". Unused in other
245 unsigned int compound_assignment : 1;
246 /* Only used by a field expression; if set, indicates that the field
247 name occurred at the end of the expression and is eligible for
249 unsigned int completing : 1;
250 /* Operands of expression. Which one is used and how depends on the
251 particular opcode. */
260 %token <sval> COMPLETE
261 %token <typed_val_int> INTEGER
262 %token <typed_val_int> DECIMAL_INTEGER
264 %token <sval> BYTESTRING
265 %token <typed_val_float> FLOAT
266 %token <opcode> COMPOUND_ASSIGN
268 /* Keyword tokens. */
269 %token <voidval> KW_AS
270 %token <voidval> KW_IF
271 %token <voidval> KW_TRUE
272 %token <voidval> KW_FALSE
273 %token <voidval> KW_SUPER
274 %token <voidval> KW_SELF
275 %token <voidval> KW_MUT
276 %token <voidval> KW_EXTERN
277 %token <voidval> KW_CONST
278 %token <voidval> KW_FN
280 /* Operator tokens. */
281 %token <voidval> DOTDOT
282 %token <voidval> OROR
283 %token <voidval> ANDAND
284 %token <voidval> EQEQ
285 %token <voidval> NOTEQ
286 %token <voidval> LTEQ
287 %token <voidval> GTEQ
288 %token <voidval> LSH RSH
289 %token <voidval> COLONCOLON
290 %token <voidval> ARROW
293 %type <op> path_for_expr
294 %type <op> identifier_path_for_expr
295 %type <op> path_for_type
296 %type <op> identifier_path_for_type
297 %type <op> just_identifiers_for_type
299 %type <params> maybe_type_list
300 %type <params> type_list
302 %type <depth> super_path
306 %type <op> field_expr
309 %type <op> binop_expr
310 %type <op> binop_expr_expr
311 %type <op> type_cast_expr
312 %type <op> assignment_expr
313 %type <op> compound_assignment_expr
314 %type <op> paren_expr
317 %type <op> tuple_expr
319 %type <op> struct_expr
320 %type <op> array_expr
321 %type <op> range_expr
323 %type <params> expr_list
324 %type <params> maybe_expr_list
325 %type <params> paren_expr_list
327 %type <field_inits> struct_expr_list
328 %type <one_field_init> struct_expr_tail
332 %right '=' COMPOUND_ASSIGN
335 %nonassoc EQEQ NOTEQ '<' '>' LTEQ GTEQ
343 /* These could be %precedence in Bison, but that isn't a yacc
354 /* If we are completing and see a valid parse,
355 rust_ast will already have been set. */
356 if (rust_ast == NULL)
361 /* Note that the Rust grammar includes a method_call_expr, but we
362 handle this differently, to avoid a shift/reduce conflict with
381 '(' expr ',' maybe_expr_list ')'
383 VEC_safe_insert (rust_op_ptr, *$4, 0, $2);
384 error (_("Tuple expressions not supported yet"));
391 struct typed_val_int val;
394 = language_lookup_primitive_type (parse_language (pstate),
395 parse_gdbarch (pstate),
398 $$ = ast_literal (val);
402 /* To avoid a shift/reduce conflict with call_expr, we don't handle
403 tuple struct expressions here, but instead when examining the
406 path_for_expr '{' struct_expr_list '}'
407 { $$ = ast_struct ($1, $3); }
434 VEC (set_field) **result
435 = OBSTACK_ZALLOC (&work_obstack, VEC (set_field) *);
440 VEC (set_field) **result
441 = OBSTACK_ZALLOC (&work_obstack, VEC (set_field) *);
443 make_cleanup (VEC_cleanup (set_field), result);
444 VEC_safe_push (set_field, *result, &$1);
448 | IDENT ':' expr ',' struct_expr_list
454 VEC_safe_push (set_field, *$5, &sf);
460 '[' KW_MUT expr_list ']'
461 { $$ = ast_call_ish (OP_ARRAY, NULL, $3); }
463 { $$ = ast_call_ish (OP_ARRAY, NULL, $2); }
464 | '[' KW_MUT expr ';' expr ']'
465 { $$ = ast_operation (OP_RUST_ARRAY, $3, $5); }
466 | '[' expr ';' expr ']'
467 { $$ = ast_operation (OP_RUST_ARRAY, $2, $4); }
472 { $$ = ast_range ($1, NULL); }
474 { $$ = ast_range ($1, $3); }
476 { $$ = ast_range (NULL, $2); }
478 { $$ = ast_range (NULL, NULL); }
483 { $$ = ast_literal ($1); }
485 { $$ = ast_literal ($1); }
487 { $$ = ast_dliteral ($1); }
490 const struct rust_op *str = ast_string ($1);
491 VEC (set_field) **fields;
492 struct set_field field;
493 struct typed_val_int val;
496 fields = OBSTACK_ZALLOC (&work_obstack, VEC (set_field) *);
497 make_cleanup (VEC_cleanup (set_field), fields);
499 /* Wrap the raw string in the &str struct. */
500 field.name.ptr = "data_ptr";
501 field.name.length = strlen (field.name.ptr);
502 field.init = ast_unary (UNOP_ADDR, ast_string ($1));
503 VEC_safe_push (set_field, *fields, &field);
505 val.type = rust_type ("usize");
508 field.name.ptr = "length";
509 field.name.length = strlen (field.name.ptr);
510 field.init = ast_literal (val);
511 VEC_safe_push (set_field, *fields, &field);
514 token.length = strlen (token.ptr);
515 $$ = ast_struct (ast_path (token, NULL), fields);
518 { $$ = ast_string ($1); }
521 struct typed_val_int val;
523 val.type = language_bool_type (parse_language (pstate),
524 parse_gdbarch (pstate));
526 $$ = ast_literal (val);
530 struct typed_val_int val;
532 val.type = language_bool_type (parse_language (pstate),
533 parse_gdbarch (pstate));
535 $$ = ast_literal (val);
541 { $$ = ast_structop ($1, $3.ptr, 0); }
544 $$ = ast_structop ($1, $3.ptr, 1);
547 | expr '.' DECIMAL_INTEGER
548 { $$ = ast_structop_anonymous ($1, $3); }
553 { $$ = ast_operation (BINOP_SUBSCRIPT, $1, $3); }
558 { $$ = ast_unary (UNOP_PLUS, $2); }
560 | '-' expr %prec UNARY
561 { $$ = ast_unary (UNOP_NEG, $2); }
563 | '!' expr %prec UNARY
565 /* Note that we provide a Rust-specific evaluator
566 override for UNOP_COMPLEMENT, so it can do the
567 right thing for both bool and integral
569 $$ = ast_unary (UNOP_COMPLEMENT, $2);
572 | '*' expr %prec UNARY
573 { $$ = ast_unary (UNOP_IND, $2); }
575 | '&' expr %prec UNARY
576 { $$ = ast_unary (UNOP_ADDR, $2); }
578 | '&' KW_MUT expr %prec UNARY
579 { $$ = ast_unary (UNOP_ADDR, $3); }
587 | compound_assignment_expr
592 { $$ = ast_operation (BINOP_MUL, $1, $3); }
595 { $$ = ast_operation (BINOP_REPEAT, $1, $3); }
598 { $$ = ast_operation (BINOP_DIV, $1, $3); }
601 { $$ = ast_operation (BINOP_REM, $1, $3); }
604 { $$ = ast_operation (BINOP_LESS, $1, $3); }
607 { $$ = ast_operation (BINOP_GTR, $1, $3); }
610 { $$ = ast_operation (BINOP_BITWISE_AND, $1, $3); }
613 { $$ = ast_operation (BINOP_BITWISE_IOR, $1, $3); }
616 { $$ = ast_operation (BINOP_BITWISE_XOR, $1, $3); }
619 { $$ = ast_operation (BINOP_ADD, $1, $3); }
622 { $$ = ast_operation (BINOP_SUB, $1, $3); }
625 { $$ = ast_operation (BINOP_LOGICAL_OR, $1, $3); }
628 { $$ = ast_operation (BINOP_LOGICAL_AND, $1, $3); }
631 { $$ = ast_operation (BINOP_EQUAL, $1, $3); }
634 { $$ = ast_operation (BINOP_NOTEQUAL, $1, $3); }
637 { $$ = ast_operation (BINOP_LEQ, $1, $3); }
640 { $$ = ast_operation (BINOP_GEQ, $1, $3); }
643 { $$ = ast_operation (BINOP_LSH, $1, $3); }
646 { $$ = ast_operation (BINOP_RSH, $1, $3); }
651 { $$ = ast_cast ($1, $3); }
656 { $$ = ast_operation (BINOP_ASSIGN, $1, $3); }
659 compound_assignment_expr:
660 expr COMPOUND_ASSIGN expr
661 { $$ = ast_compound_assignment ($2, $1, $3); }
673 $$ = OBSTACK_ZALLOC (&work_obstack, VEC (rust_op_ptr) *);
674 make_cleanup (VEC_cleanup (rust_op_ptr), $$);
675 VEC_safe_push (rust_op_ptr, *$$, $1);
679 VEC_safe_push (rust_op_ptr, *$1, $3);
687 /* The result can't be NULL. */
688 $$ = OBSTACK_ZALLOC (&work_obstack, VEC (rust_op_ptr) *);
689 make_cleanup (VEC_cleanup (rust_op_ptr), $$);
704 { $$ = ast_call_ish (OP_FUNCALL, $1, $2); }
715 | super_path KW_SUPER COLONCOLON
723 { $$ = ast_path ($1, NULL); }
725 { $$ = ast_path (make_stoken ("self"), NULL); }
729 identifier_path_for_expr
730 | KW_SELF COLONCOLON identifier_path_for_expr
731 { $$ = super_name ($3, 0); }
732 | maybe_self_path super_path identifier_path_for_expr
733 { $$ = super_name ($3, $2); }
734 | COLONCOLON identifier_path_for_expr
735 { $$ = crate_name ($2); }
736 | KW_EXTERN identifier_path_for_expr
738 /* This is a gdb extension to make it possible to
739 refer to items in other crates. It just bypasses
740 adding the current crate to the front of the
742 $$ = ast_path (rust_concat3 ("::", $2->left.sval.ptr, NULL),
747 identifier_path_for_expr:
749 { $$ = ast_path ($1, NULL); }
750 | identifier_path_for_expr COLONCOLON IDENT
752 $$ = ast_path (rust_concat3 ($1->left.sval.ptr, "::",
756 | identifier_path_for_expr COLONCOLON '<' type_list '>'
757 { $$ = ast_path ($1->left.sval, $4); }
758 | identifier_path_for_expr COLONCOLON '<' type_list RSH
760 $$ = ast_path ($1->left.sval, $4);
761 rust_push_back ('>');
766 identifier_path_for_type
767 | KW_SELF COLONCOLON identifier_path_for_type
768 { $$ = super_name ($3, 0); }
769 | maybe_self_path super_path identifier_path_for_type
770 { $$ = super_name ($3, $2); }
771 | COLONCOLON identifier_path_for_type
772 { $$ = crate_name ($2); }
773 | KW_EXTERN identifier_path_for_type
775 /* This is a gdb extension to make it possible to
776 refer to items in other crates. It just bypasses
777 adding the current crate to the front of the
779 $$ = ast_path (rust_concat3 ("::", $2->left.sval.ptr, NULL),
784 just_identifiers_for_type:
786 { $$ = ast_path ($1, NULL); }
787 | just_identifiers_for_type COLONCOLON IDENT
789 $$ = ast_path (rust_concat3 ($1->left.sval.ptr, "::",
795 identifier_path_for_type:
796 just_identifiers_for_type
797 | just_identifiers_for_type '<' type_list '>'
798 { $$ = ast_path ($1->left.sval, $3); }
799 | just_identifiers_for_type '<' type_list RSH
801 $$ = ast_path ($1->left.sval, $3);
802 rust_push_back ('>');
808 | '[' type ';' INTEGER ']'
809 { $$ = ast_array_type ($2, $4); }
810 | '[' type ';' DECIMAL_INTEGER ']'
811 { $$ = ast_array_type ($2, $4); }
813 { $$ = ast_slice_type ($3); }
815 { $$ = ast_reference_type ($2); }
817 { $$ = ast_pointer_type ($3, 1); }
819 { $$ = ast_pointer_type ($3, 0); }
820 | KW_FN '(' maybe_type_list ')' ARROW type
821 { $$ = ast_function_type ($6, $3); }
822 | '(' maybe_type_list ')'
823 { $$ = ast_tuple_type ($2); }
836 VEC (rust_op_ptr) **result
837 = OBSTACK_ZALLOC (&work_obstack, VEC (rust_op_ptr) *);
839 make_cleanup (VEC_cleanup (rust_op_ptr), result);
840 VEC_safe_push (rust_op_ptr, *result, $1);
845 VEC_safe_push (rust_op_ptr, *$1, $3);
852 /* A struct of this type is used to describe a token. */
858 enum exp_opcode opcode;
861 /* Identifier tokens. */
863 static const struct token_info identifier_tokens[] =
865 { "as", KW_AS, OP_NULL },
866 { "false", KW_FALSE, OP_NULL },
867 { "if", 0, OP_NULL },
868 { "mut", KW_MUT, OP_NULL },
869 { "const", KW_CONST, OP_NULL },
870 { "self", KW_SELF, OP_NULL },
871 { "super", KW_SUPER, OP_NULL },
872 { "true", KW_TRUE, OP_NULL },
873 { "extern", KW_EXTERN, OP_NULL },
874 { "fn", KW_FN, OP_NULL },
877 /* Operator tokens, sorted longest first. */
879 static const struct token_info operator_tokens[] =
881 { ">>=", COMPOUND_ASSIGN, BINOP_RSH },
882 { "<<=", COMPOUND_ASSIGN, BINOP_LSH },
884 { "<<", LSH, OP_NULL },
885 { ">>", RSH, OP_NULL },
886 { "&&", ANDAND, OP_NULL },
887 { "||", OROR, OP_NULL },
888 { "==", EQEQ, OP_NULL },
889 { "!=", NOTEQ, OP_NULL },
890 { "<=", LTEQ, OP_NULL },
891 { ">=", GTEQ, OP_NULL },
892 { "+=", COMPOUND_ASSIGN, BINOP_ADD },
893 { "-=", COMPOUND_ASSIGN, BINOP_SUB },
894 { "*=", COMPOUND_ASSIGN, BINOP_MUL },
895 { "/=", COMPOUND_ASSIGN, BINOP_DIV },
896 { "%=", COMPOUND_ASSIGN, BINOP_REM },
897 { "&=", COMPOUND_ASSIGN, BINOP_BITWISE_AND },
898 { "|=", COMPOUND_ASSIGN, BINOP_BITWISE_IOR },
899 { "^=", COMPOUND_ASSIGN, BINOP_BITWISE_XOR },
901 { "::", COLONCOLON, OP_NULL },
902 { "..", DOTDOT, OP_NULL },
903 { "->", ARROW, OP_NULL }
906 /* Helper function to copy to the name obstack. */
909 rust_copy_name (const char *name, int len)
911 return (const char *) obstack_copy0 (&work_obstack, name, len);
914 /* Helper function to make an stoken from a C string. */
917 make_stoken (const char *p)
919 struct stoken result;
922 result.length = strlen (result.ptr);
926 /* Helper function to concatenate three strings on the name
930 rust_concat3 (const char *s1, const char *s2, const char *s3)
932 return make_stoken (obconcat (&work_obstack, s1, s2, s3, (char *) NULL));
935 /* Return an AST node referring to NAME, but relative to the crate's
938 static const struct rust_op *
939 crate_name (const struct rust_op *name)
941 char *crate = rust_crate_for_block (expression_context_block);
942 struct stoken result;
944 gdb_assert (name->opcode == OP_VAR_VALUE);
947 error (_("Could not find crate for current location"));
948 result = make_stoken (obconcat (&work_obstack, "::", crate, "::",
949 name->left.sval.ptr, (char *) NULL));
952 return ast_path (result, name->right.params);
955 /* Create an AST node referring to a "super::" qualified name. IDENT
956 is the base name and N_SUPERS is how many "super::"s were
957 provided. N_SUPERS can be zero. */
959 static const struct rust_op *
960 super_name (const struct rust_op *ident, unsigned int n_supers)
962 const char *scope = block_scope (expression_context_block);
965 gdb_assert (ident->opcode == OP_VAR_VALUE);
967 if (scope[0] == '\0')
968 error (_("Couldn't find namespace scope for self::"));
974 VEC (int) *offsets = NULL;
975 unsigned int current_len;
976 struct cleanup *cleanup;
978 cleanup = make_cleanup (VEC_cleanup (int), &offsets);
979 current_len = cp_find_first_component (scope);
980 while (scope[current_len] != '\0')
982 VEC_safe_push (int, offsets, current_len);
983 gdb_assert (scope[current_len] == ':');
986 current_len += cp_find_first_component (scope
990 len = VEC_length (int, offsets);
992 error (_("Too many super:: uses from '%s'"), scope);
994 offset = VEC_index (int, offsets, len - n_supers);
996 do_cleanups (cleanup);
999 offset = strlen (scope);
1001 obstack_grow (&work_obstack, "::", 2);
1002 obstack_grow (&work_obstack, scope, offset);
1003 obstack_grow (&work_obstack, "::", 2);
1004 obstack_grow0 (&work_obstack, ident->left.sval.ptr, ident->left.sval.length);
1006 return ast_path (make_stoken ((const char *) obstack_finish (&work_obstack)),
1007 ident->right.params);
1010 /* A helper that updates innermost_block as appropriate. */
1013 update_innermost_block (struct block_symbol sym)
1015 if (symbol_read_needs_frame (sym.symbol)
1016 && (innermost_block == NULL
1017 || contained_in (sym.block, innermost_block)))
1018 innermost_block = sym.block;
1021 /* A helper to look up a Rust type, or fail. This only works for
1022 types defined by rust_language_arch_info. */
1024 static struct type *
1025 rust_type (const char *name)
1029 /* When unit testing, we don't bother checking the types, so avoid a
1030 possibly-failing lookup here. */
1034 type = language_lookup_primitive_type (parse_language (pstate),
1035 parse_gdbarch (pstate),
1038 error (_("Could not find Rust type %s"), name);
1042 /* Lex a hex number with at least MIN digits and at most MAX
1046 lex_hex (int min, int max)
1048 uint32_t result = 0;
1050 /* We only want to stop at MAX if we're lexing a byte escape. */
1051 int check_max = min == max;
1053 while ((check_max ? len <= max : 1)
1054 && ((lexptr[0] >= 'a' && lexptr[0] <= 'f')
1055 || (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1056 || (lexptr[0] >= '0' && lexptr[0] <= '9')))
1059 if (lexptr[0] >= 'a' && lexptr[0] <= 'f')
1060 result = result + 10 + lexptr[0] - 'a';
1061 else if (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1062 result = result + 10 + lexptr[0] - 'A';
1064 result = result + lexptr[0] - '0';
1070 error (_("Not enough hex digits seen"));
1073 gdb_assert (min != max);
1074 error (_("Overlong hex escape"));
1080 /* Lex an escape. IS_BYTE is true if we're lexing a byte escape;
1081 otherwise we're lexing a character escape. */
1084 lex_escape (int is_byte)
1088 gdb_assert (lexptr[0] == '\\');
1094 result = lex_hex (2, 2);
1099 error (_("Unicode escape in byte literal"));
1101 if (lexptr[0] != '{')
1102 error (_("Missing '{' in Unicode escape"));
1104 result = lex_hex (1, 6);
1105 /* Could do range checks here. */
1106 if (lexptr[0] != '}')
1107 error (_("Missing '}' in Unicode escape"));
1141 error (_("Invalid escape \\%c in literal"), lexptr[0]);
1147 /* Lex a character constant. */
1150 lex_character (void)
1155 if (lexptr[0] == 'b')
1160 gdb_assert (lexptr[0] == '\'');
1162 /* This should handle UTF-8 here. */
1163 if (lexptr[0] == '\\')
1164 value = lex_escape (is_byte);
1167 value = lexptr[0] & 0xff;
1171 if (lexptr[0] != '\'')
1172 error (_("Unterminated character literal"));
1175 rustyylval.typed_val_int.val = value;
1176 rustyylval.typed_val_int.type = rust_type (is_byte ? "u8" : "char");
1181 /* Return the offset of the double quote if STR looks like the start
1182 of a raw string, or 0 if STR does not start a raw string. */
1185 starts_raw_string (const char *str)
1187 const char *save = str;
1192 while (str[0] == '#')
1199 /* Return true if STR looks like the end of a raw string that had N
1200 hashes at the start. */
1203 ends_raw_string (const char *str, int n)
1207 gdb_assert (str[0] == '"');
1208 for (i = 0; i < n; ++i)
1209 if (str[i + 1] != '#')
1214 /* Lex a string constant. */
1219 int is_byte = lexptr[0] == 'b';
1221 int len_in_chars = 0;
1225 raw_length = starts_raw_string (lexptr);
1226 lexptr += raw_length;
1227 gdb_assert (lexptr[0] == '"');
1236 if (lexptr[0] == '"' && ends_raw_string (lexptr, raw_length - 1))
1238 /* Exit with lexptr pointing after the final "#". */
1239 lexptr += raw_length;
1242 else if (lexptr[0] == '\0')
1243 error (_("Unexpected EOF in string"));
1245 value = lexptr[0] & 0xff;
1246 if (is_byte && value > 127)
1247 error (_("Non-ASCII value in raw byte string"));
1248 obstack_1grow (&work_obstack, value);
1252 else if (lexptr[0] == '"')
1254 /* Make sure to skip the quote. */
1258 else if (lexptr[0] == '\\')
1260 value = lex_escape (is_byte);
1263 obstack_1grow (&work_obstack, value);
1265 convert_between_encodings ("UTF-32", "UTF-8", (gdb_byte *) &value,
1266 sizeof (value), sizeof (value),
1267 &work_obstack, translit_none);
1269 else if (lexptr[0] == '\0')
1270 error (_("Unexpected EOF in string"));
1273 value = lexptr[0] & 0xff;
1274 if (is_byte && value > 127)
1275 error (_("Non-ASCII value in byte string"));
1276 obstack_1grow (&work_obstack, value);
1281 rustyylval.sval.length = obstack_object_size (&work_obstack);
1282 rustyylval.sval.ptr = (const char *) obstack_finish (&work_obstack);
1283 return is_byte ? BYTESTRING : STRING;
1286 /* Return true if STRING starts with whitespace followed by a digit. */
1289 space_then_number (const char *string)
1291 const char *p = string;
1293 while (p[0] == ' ' || p[0] == '\t')
1298 return *p >= '0' && *p <= '9';
1301 /* Return true if C can start an identifier. */
1304 rust_identifier_start_p (char c)
1306 return ((c >= 'a' && c <= 'z')
1307 || (c >= 'A' && c <= 'Z')
1312 /* Lex an identifier. */
1315 lex_identifier (void)
1317 const char *start = lexptr;
1318 unsigned int length;
1319 const struct token_info *token;
1321 int is_gdb_var = lexptr[0] == '$';
1323 gdb_assert (rust_identifier_start_p (lexptr[0]));
1327 /* For the time being this doesn't handle Unicode rules. Non-ASCII
1328 identifiers are gated anyway. */
1329 while ((lexptr[0] >= 'a' && lexptr[0] <= 'z')
1330 || (lexptr[0] >= 'A' && lexptr[0] <= 'Z')
1332 || (is_gdb_var && lexptr[0] == '$')
1333 || (lexptr[0] >= '0' && lexptr[0] <= '9'))
1337 length = lexptr - start;
1339 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
1341 if (length == strlen (identifier_tokens[i].name)
1342 && strncmp (identifier_tokens[i].name, start, length) == 0)
1344 token = &identifier_tokens[i];
1351 if (token->value == 0)
1353 /* Leave the terminating token alone. */
1358 else if (token == NULL
1359 && (strncmp (start, "thread", length) == 0
1360 || strncmp (start, "task", length) == 0)
1361 && space_then_number (lexptr))
1363 /* "task" or "thread" followed by a number terminates the
1364 parse, per gdb rules. */
1369 if (token == NULL || (parse_completion && lexptr[0] == '\0'))
1370 rustyylval.sval = make_stoken (rust_copy_name (start, length));
1372 if (parse_completion && lexptr[0] == '\0')
1374 /* Prevent rustyylex from returning two COMPLETE tokens. */
1375 prev_lexptr = lexptr;
1380 return token->value;
1386 /* Lex an operator. */
1391 const struct token_info *token = NULL;
1394 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
1396 if (strncmp (operator_tokens[i].name, lexptr,
1397 strlen (operator_tokens[i].name)) == 0)
1399 lexptr += strlen (operator_tokens[i].name);
1400 token = &operator_tokens[i];
1407 rustyylval.opcode = token->opcode;
1408 return token->value;
1419 regmatch_t subexps[NUM_SUBEXPRESSIONS];
1422 int could_be_decimal = 1;
1423 int implicit_i32 = 0;
1424 char *type_name = NULL;
1427 int type_index = -1;
1430 struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
1432 match = regexec (&number_regex, lexptr, ARRAY_SIZE (subexps), subexps, 0);
1433 /* Failure means the regexp is broken. */
1434 gdb_assert (match == 0);
1436 if (subexps[INT_TEXT].rm_so != -1)
1438 /* Integer part matched. */
1440 end_index = subexps[INT_TEXT].rm_eo;
1441 if (subexps[INT_TYPE].rm_so == -1)
1448 type_index = INT_TYPE;
1449 could_be_decimal = 0;
1452 else if (subexps[FLOAT_TYPE1].rm_so != -1)
1454 /* Found floating point type suffix. */
1455 end_index = subexps[FLOAT_TYPE1].rm_so;
1456 type_index = FLOAT_TYPE1;
1458 else if (subexps[FLOAT_TYPE2].rm_so != -1)
1460 /* Found floating point type suffix. */
1461 end_index = subexps[FLOAT_TYPE2].rm_so;
1462 type_index = FLOAT_TYPE2;
1466 /* Any other floating point match. */
1467 end_index = subexps[0].rm_eo;
1471 /* We need a special case if the final character is ".". In this
1472 case we might need to parse an integer. For example, "23.f()" is
1473 a request for a trait method call, not a syntax error involving
1474 the floating point number "23.". */
1475 gdb_assert (subexps[0].rm_eo > 0);
1476 if (lexptr[subexps[0].rm_eo - 1] == '.')
1478 const char *next = skip_spaces_const (&lexptr[subexps[0].rm_eo]);
1480 if (rust_identifier_start_p (*next) || *next == '.')
1484 end_index = subexps[0].rm_eo;
1486 could_be_decimal = 1;
1491 /* Compute the type name if we haven't already. */
1492 if (type_name == NULL)
1494 gdb_assert (type_index != -1);
1495 type_name = xstrndup (lexptr + subexps[type_index].rm_so,
1496 (subexps[type_index].rm_eo
1497 - subexps[type_index].rm_so));
1498 make_cleanup (xfree, type_name);
1501 /* Look up the type. */
1502 type = rust_type (type_name);
1504 /* Copy the text of the number and remove the "_"s. */
1505 number = xstrndup (lexptr, end_index);
1506 make_cleanup (xfree, number);
1507 for (i = out = 0; number[i]; ++i)
1509 if (number[i] == '_')
1510 could_be_decimal = 0;
1512 number[out++] = number[i];
1516 /* Advance past the match. */
1517 lexptr += subexps[0].rm_eo;
1519 /* Parse the number. */
1524 if (number[0] == '0')
1526 if (number[1] == 'x')
1528 else if (number[1] == 'o')
1530 else if (number[1] == 'b')
1535 could_be_decimal = 0;
1539 value = strtoul (number, NULL, radix);
1540 if (implicit_i32 && value >= ((uint64_t) 1) << 31)
1541 type = rust_type ("i64");
1543 rustyylval.typed_val_int.val = value;
1544 rustyylval.typed_val_int.type = type;
1548 rustyylval.typed_val_float.dval = strtod (number, NULL);
1549 rustyylval.typed_val_float.type = type;
1552 do_cleanups (cleanup);
1553 return is_integer ? (could_be_decimal ? DECIMAL_INTEGER : INTEGER) : FLOAT;
1561 /* Skip all leading whitespace. */
1562 while (lexptr[0] == ' ' || lexptr[0] == '\t' || lexptr[0] == '\r'
1563 || lexptr[0] == '\n')
1566 /* If we hit EOF and we're completing, then return COMPLETE -- maybe
1567 we're completing an empty string at the end of a field_expr.
1568 But, we don't want to return two COMPLETE tokens in a row. */
1569 if (lexptr[0] == '\0' && lexptr == prev_lexptr)
1571 prev_lexptr = lexptr;
1572 if (lexptr[0] == '\0')
1574 if (parse_completion)
1576 rustyylval.sval = make_stoken ("");
1582 if (lexptr[0] >= '0' && lexptr[0] <= '9')
1583 return lex_number ();
1584 else if (lexptr[0] == 'b' && lexptr[1] == '\'')
1585 return lex_character ();
1586 else if (lexptr[0] == 'b' && lexptr[1] == '"')
1587 return lex_string ();
1588 else if (lexptr[0] == 'b' && starts_raw_string (lexptr + 1))
1589 return lex_string ();
1590 else if (starts_raw_string (lexptr))
1591 return lex_string ();
1592 else if (rust_identifier_start_p (lexptr[0]))
1593 return lex_identifier ();
1594 else if (lexptr[0] == '"')
1595 return lex_string ();
1596 else if (lexptr[0] == '\'')
1597 return lex_character ();
1598 else if (lexptr[0] == '}' || lexptr[0] == ']')
1600 /* Falls through to lex_operator. */
1603 else if (lexptr[0] == '(' || lexptr[0] == '{')
1605 /* Falls through to lex_operator. */
1608 else if (lexptr[0] == ',' && comma_terminates && paren_depth == 0)
1611 return lex_operator ();
1614 /* Push back a single character to be re-lexed. */
1617 rust_push_back (char c)
1619 /* Can't be called before any lexing. */
1620 gdb_assert (prev_lexptr != NULL);
1623 gdb_assert (*lexptr == c);
1628 /* Make an arbitrary operation and fill in the fields. */
1630 static const struct rust_op *
1631 ast_operation (enum exp_opcode opcode, const struct rust_op *left,
1632 const struct rust_op *right)
1634 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1636 result->opcode = opcode;
1637 result->left.op = left;
1638 result->right.op = right;
1643 /* Make a compound assignment operation. */
1645 static const struct rust_op *
1646 ast_compound_assignment (enum exp_opcode opcode, const struct rust_op *left,
1647 const struct rust_op *right)
1649 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1651 result->opcode = opcode;
1652 result->compound_assignment = 1;
1653 result->left.op = left;
1654 result->right.op = right;
1659 /* Make a typed integer literal operation. */
1661 static const struct rust_op *
1662 ast_literal (struct typed_val_int val)
1664 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1666 result->opcode = OP_LONG;
1667 result->left.typed_val_int = val;
1672 /* Make a typed floating point literal operation. */
1674 static const struct rust_op *
1675 ast_dliteral (struct typed_val_float val)
1677 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1679 result->opcode = OP_DOUBLE;
1680 result->left.typed_val_float = val;
1685 /* Make a unary operation. */
1687 static const struct rust_op *
1688 ast_unary (enum exp_opcode opcode, const struct rust_op *expr)
1690 return ast_operation (opcode, expr, NULL);
1693 /* Make a cast operation. */
1695 static const struct rust_op *
1696 ast_cast (const struct rust_op *expr, const struct rust_op *type)
1698 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1700 result->opcode = UNOP_CAST;
1701 result->left.op = expr;
1702 result->right.op = type;
1707 /* Make a call-like operation. This is nominally a function call, but
1708 when lowering we may discover that it actually represents the
1709 creation of a tuple struct. */
1711 static const struct rust_op *
1712 ast_call_ish (enum exp_opcode opcode, const struct rust_op *expr,
1713 VEC (rust_op_ptr) **params)
1715 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1717 result->opcode = opcode;
1718 result->left.op = expr;
1719 result->right.params = params;
1724 /* Make a structure creation operation. */
1726 static const struct rust_op *
1727 ast_struct (const struct rust_op *name, VEC (set_field) **fields)
1729 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1731 result->opcode = OP_AGGREGATE;
1732 result->left.op = name;
1733 result->right.field_inits = fields;
1738 /* Make an identifier path. */
1740 static const struct rust_op *
1741 ast_path (struct stoken path, VEC (rust_op_ptr) **params)
1743 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1745 result->opcode = OP_VAR_VALUE;
1746 result->left.sval = path;
1747 result->right.params = params;
1752 /* Make a string constant operation. */
1754 static const struct rust_op *
1755 ast_string (struct stoken str)
1757 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1759 result->opcode = OP_STRING;
1760 result->left.sval = str;
1765 /* Make a field expression. */
1767 static const struct rust_op *
1768 ast_structop (const struct rust_op *left, const char *name, int completing)
1770 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1772 result->opcode = STRUCTOP_STRUCT;
1773 result->completing = completing;
1774 result->left.op = left;
1775 result->right.sval = make_stoken (name);
1780 /* Make an anonymous struct operation, like 'x.0'. */
1782 static const struct rust_op *
1783 ast_structop_anonymous (const struct rust_op *left,
1784 struct typed_val_int number)
1786 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1788 result->opcode = STRUCTOP_ANONYMOUS;
1789 result->left.op = left;
1790 result->right.typed_val_int = number;
1795 /* Make a range operation. */
1797 static const struct rust_op *
1798 ast_range (const struct rust_op *lhs, const struct rust_op *rhs)
1800 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1802 result->opcode = OP_RANGE;
1803 result->left.op = lhs;
1804 result->right.op = rhs;
1809 /* A helper function to make a type-related AST node. */
1811 static struct rust_op *
1812 ast_basic_type (enum type_code typecode)
1814 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1816 result->opcode = OP_TYPE;
1817 result->typecode = typecode;
1821 /* Create an AST node describing an array type. */
1823 static const struct rust_op *
1824 ast_array_type (const struct rust_op *lhs, struct typed_val_int val)
1826 struct rust_op *result = ast_basic_type (TYPE_CODE_ARRAY);
1828 result->left.op = lhs;
1829 result->right.typed_val_int = val;
1833 /* Create an AST node describing a reference type. */
1835 static const struct rust_op *
1836 ast_slice_type (const struct rust_op *type)
1838 /* Use TYPE_CODE_COMPLEX just because it is handy. */
1839 struct rust_op *result = ast_basic_type (TYPE_CODE_COMPLEX);
1841 result->left.op = type;
1845 /* Create an AST node describing a reference type. */
1847 static const struct rust_op *
1848 ast_reference_type (const struct rust_op *type)
1850 struct rust_op *result = ast_basic_type (TYPE_CODE_REF);
1852 result->left.op = type;
1856 /* Create an AST node describing a pointer type. */
1858 static const struct rust_op *
1859 ast_pointer_type (const struct rust_op *type, int is_mut)
1861 struct rust_op *result = ast_basic_type (TYPE_CODE_PTR);
1863 result->left.op = type;
1864 /* For the time being we ignore is_mut. */
1868 /* Create an AST node describing a function type. */
1870 static const struct rust_op *
1871 ast_function_type (const struct rust_op *rtype, VEC (rust_op_ptr) **params)
1873 struct rust_op *result = ast_basic_type (TYPE_CODE_FUNC);
1875 result->left.op = rtype;
1876 result->right.params = params;
1880 /* Create an AST node describing a tuple type. */
1882 static const struct rust_op *
1883 ast_tuple_type (VEC (rust_op_ptr) **params)
1885 struct rust_op *result = ast_basic_type (TYPE_CODE_STRUCT);
1887 result->left.params = params;
1891 /* A helper to appropriately munge NAME and BLOCK depending on the
1892 presence of a leading "::". */
1895 munge_name_and_block (const char **name, const struct block **block)
1897 /* If it is a global reference, skip the current block in favor of
1898 the static block. */
1899 if (strncmp (*name, "::", 2) == 0)
1902 *block = block_static_block (*block);
1906 /* Like lookup_symbol, but handles Rust namespace conventions, and
1907 doesn't require field_of_this_result. */
1909 static struct block_symbol
1910 rust_lookup_symbol (const char *name, const struct block *block,
1911 const domain_enum domain)
1913 struct block_symbol result;
1915 munge_name_and_block (&name, &block);
1917 result = lookup_symbol (name, block, domain, NULL);
1918 if (result.symbol != NULL)
1919 update_innermost_block (result);
1923 /* Look up a type, following Rust namespace conventions. */
1925 static struct type *
1926 rust_lookup_type (const char *name, const struct block *block)
1928 struct block_symbol result;
1931 munge_name_and_block (&name, &block);
1933 result = lookup_symbol (name, block, STRUCT_DOMAIN, NULL);
1934 if (result.symbol != NULL)
1936 update_innermost_block (result);
1937 return SYMBOL_TYPE (result.symbol);
1940 type = lookup_typename (parse_language (pstate), parse_gdbarch (pstate),
1945 /* Last chance, try a built-in type. */
1946 return language_lookup_primitive_type (parse_language (pstate),
1947 parse_gdbarch (pstate),
1951 static struct type *convert_ast_to_type (struct parser_state *state,
1952 const struct rust_op *operation);
1953 static const char *convert_name (struct parser_state *state,
1954 const struct rust_op *operation);
1956 /* Convert a vector of rust_ops representing types to a vector of
1959 static VEC (type_ptr) *
1960 convert_params_to_types (struct parser_state *state, VEC (rust_op_ptr) *params)
1963 const struct rust_op *op;
1964 VEC (type_ptr) *result = NULL;
1965 struct cleanup *cleanup = make_cleanup (VEC_cleanup (type_ptr), &result);
1967 for (i = 0; VEC_iterate (rust_op_ptr, params, i, op); ++i)
1968 VEC_safe_push (type_ptr, result, convert_ast_to_type (state, op));
1970 discard_cleanups (cleanup);
1974 /* Convert a rust_op representing a type to a struct type *. */
1976 static struct type *
1977 convert_ast_to_type (struct parser_state *state,
1978 const struct rust_op *operation)
1980 struct type *type, *result = NULL;
1982 if (operation->opcode == OP_VAR_VALUE)
1984 const char *varname = convert_name (state, operation);
1986 result = rust_lookup_type (varname, expression_context_block);
1988 error (_("No typed name '%s' in current context"), varname);
1992 gdb_assert (operation->opcode == OP_TYPE);
1994 switch (operation->typecode)
1996 case TYPE_CODE_ARRAY:
1997 type = convert_ast_to_type (state, operation->left.op);
1998 if (operation->right.typed_val_int.val < 0)
1999 error (_("Negative array length"));
2000 result = lookup_array_range_type (type, 0,
2001 operation->right.typed_val_int.val - 1);
2004 case TYPE_CODE_COMPLEX:
2006 struct type *usize = rust_type ("usize");
2008 type = convert_ast_to_type (state, operation->left.op);
2009 result = rust_slice_type ("&[*gdb*]", type, usize);
2015 /* For now we treat &x and *x identically. */
2016 type = convert_ast_to_type (state, operation->left.op);
2017 result = lookup_pointer_type (type);
2020 case TYPE_CODE_FUNC:
2022 VEC (type_ptr) *args
2023 = convert_params_to_types (state, *operation->right.params);
2024 struct cleanup *cleanup
2025 = make_cleanup (VEC_cleanup (type_ptr), &args);
2026 struct type **argtypes = NULL;
2028 type = convert_ast_to_type (state, operation->left.op);
2029 if (!VEC_empty (type_ptr, args))
2030 argtypes = VEC_address (type_ptr, args);
2033 = lookup_function_type_with_arguments (type,
2034 VEC_length (type_ptr, args),
2036 result = lookup_pointer_type (result);
2038 do_cleanups (cleanup);
2042 case TYPE_CODE_STRUCT:
2044 VEC (type_ptr) *args
2045 = convert_params_to_types (state, *operation->left.params);
2046 struct cleanup *cleanup
2047 = make_cleanup (VEC_cleanup (type_ptr), &args);
2052 obstack_1grow (&work_obstack, '(');
2053 for (i = 0; VEC_iterate (type_ptr, args, i, type); ++i)
2055 char *type_name = type_to_string (type);
2058 obstack_1grow (&work_obstack, ',');
2059 obstack_grow_str (&work_obstack, type_name);
2064 obstack_grow_str0 (&work_obstack, ")");
2065 name = (const char *) obstack_finish (&work_obstack);
2067 /* We don't allow creating new tuple types (yet), but we do
2068 allow looking up existing tuple types. */
2069 result = rust_lookup_type (name, expression_context_block);
2071 error (_("could not find tuple type '%s'"), name);
2073 do_cleanups (cleanup);
2078 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_type");
2081 gdb_assert (result != NULL);
2085 /* A helper function to turn a rust_op representing a name into a full
2086 name. This applies generic arguments as needed. The returned name
2087 is allocated on the work obstack. */
2090 convert_name (struct parser_state *state, const struct rust_op *operation)
2092 VEC (type_ptr) *types;
2093 struct cleanup *cleanup;
2097 gdb_assert (operation->opcode == OP_VAR_VALUE);
2099 if (operation->right.params == NULL)
2100 return operation->left.sval.ptr;
2102 types = convert_params_to_types (state, *operation->right.params);
2103 cleanup = make_cleanup (VEC_cleanup (type_ptr), &types);
2105 obstack_grow_str (&work_obstack, operation->left.sval.ptr);
2106 obstack_1grow (&work_obstack, '<');
2107 for (i = 0; VEC_iterate (type_ptr, types, i, type); ++i)
2109 char *type_name = type_to_string (type);
2112 obstack_1grow (&work_obstack, ',');
2114 obstack_grow_str (&work_obstack, type_name);
2117 obstack_grow_str0 (&work_obstack, ">");
2119 do_cleanups (cleanup);
2121 return (const char *) obstack_finish (&work_obstack);
2124 static void convert_ast_to_expression (struct parser_state *state,
2125 const struct rust_op *operation,
2126 const struct rust_op *top);
2128 /* A helper function that converts a vec of rust_ops to a gdb
2132 convert_params_to_expression (struct parser_state *state,
2133 VEC (rust_op_ptr) *params,
2134 const struct rust_op *top)
2139 for (i = 0; VEC_iterate (rust_op_ptr, params, i, elem); ++i)
2140 convert_ast_to_expression (state, elem, top);
2143 /* Lower a rust_op to a gdb expression. STATE is the parser state.
2144 OPERATION is the operation to lower. TOP is a pointer to the
2145 top-most operation; it is used to handle the special case where the
2146 top-most expression is an identifier and can be optionally lowered
2150 convert_ast_to_expression (struct parser_state *state,
2151 const struct rust_op *operation,
2152 const struct rust_op *top)
2154 switch (operation->opcode)
2157 write_exp_elt_opcode (state, OP_LONG);
2158 write_exp_elt_type (state, operation->left.typed_val_int.type);
2159 write_exp_elt_longcst (state, operation->left.typed_val_int.val);
2160 write_exp_elt_opcode (state, OP_LONG);
2164 write_exp_elt_opcode (state, OP_DOUBLE);
2165 write_exp_elt_type (state, operation->left.typed_val_float.type);
2166 write_exp_elt_dblcst (state, operation->left.typed_val_float.dval);
2167 write_exp_elt_opcode (state, OP_DOUBLE);
2170 case STRUCTOP_STRUCT:
2172 convert_ast_to_expression (state, operation->left.op, top);
2174 if (operation->completing)
2175 mark_struct_expression (state);
2176 write_exp_elt_opcode (state, STRUCTOP_STRUCT);
2177 write_exp_string (state, operation->right.sval);
2178 write_exp_elt_opcode (state, STRUCTOP_STRUCT);
2182 case STRUCTOP_ANONYMOUS:
2184 convert_ast_to_expression (state, operation->left.op, top);
2186 write_exp_elt_opcode (state, STRUCTOP_ANONYMOUS);
2187 write_exp_elt_longcst (state, operation->right.typed_val_int.val);
2188 write_exp_elt_opcode (state, STRUCTOP_ANONYMOUS);
2194 case UNOP_COMPLEMENT:
2197 convert_ast_to_expression (state, operation->left.op, top);
2198 write_exp_elt_opcode (state, operation->opcode);
2201 case BINOP_SUBSCRIPT:
2208 case BINOP_BITWISE_AND:
2209 case BINOP_BITWISE_IOR:
2210 case BINOP_BITWISE_XOR:
2213 case BINOP_LOGICAL_OR:
2214 case BINOP_LOGICAL_AND:
2216 case BINOP_NOTEQUAL:
2223 convert_ast_to_expression (state, operation->left.op, top);
2224 convert_ast_to_expression (state, operation->right.op, top);
2225 if (operation->compound_assignment)
2227 write_exp_elt_opcode (state, BINOP_ASSIGN_MODIFY);
2228 write_exp_elt_opcode (state, operation->opcode);
2229 write_exp_elt_opcode (state, BINOP_ASSIGN_MODIFY);
2232 write_exp_elt_opcode (state, operation->opcode);
2234 if (operation->compound_assignment
2235 || operation->opcode == BINOP_ASSIGN)
2239 type = language_lookup_primitive_type (parse_language (state),
2240 parse_gdbarch (state),
2243 write_exp_elt_opcode (state, OP_LONG);
2244 write_exp_elt_type (state, type);
2245 write_exp_elt_longcst (state, 0);
2246 write_exp_elt_opcode (state, OP_LONG);
2248 write_exp_elt_opcode (state, BINOP_COMMA);
2254 struct type *type = convert_ast_to_type (state, operation->right.op);
2256 convert_ast_to_expression (state, operation->left.op, top);
2257 write_exp_elt_opcode (state, UNOP_CAST);
2258 write_exp_elt_type (state, type);
2259 write_exp_elt_opcode (state, UNOP_CAST);
2265 if (operation->left.op->opcode == OP_VAR_VALUE)
2268 const char *varname = convert_name (state, operation->left.op);
2270 type = rust_lookup_type (varname, expression_context_block);
2273 /* This is actually a tuple struct expression, not a
2277 VEC (rust_op_ptr) *params = *operation->right.params;
2279 if (TYPE_CODE (type) != TYPE_CODE_NAMESPACE)
2281 if (!rust_tuple_struct_type_p (type))
2282 error (_("Type %s is not a tuple struct"), varname);
2285 VEC_iterate (rust_op_ptr, params, i, elem);
2288 char *cell = get_print_cell ();
2290 xsnprintf (cell, PRINT_CELL_SIZE, "__%d", i);
2291 write_exp_elt_opcode (state, OP_NAME);
2292 write_exp_string (state, make_stoken (cell));
2293 write_exp_elt_opcode (state, OP_NAME);
2295 convert_ast_to_expression (state, elem, top);
2298 write_exp_elt_opcode (state, OP_AGGREGATE);
2299 write_exp_elt_type (state, type);
2300 write_exp_elt_longcst (state,
2301 2 * VEC_length (rust_op_ptr,
2303 write_exp_elt_opcode (state, OP_AGGREGATE);
2308 convert_ast_to_expression (state, operation->left.op, top);
2309 convert_params_to_expression (state, *operation->right.params, top);
2310 write_exp_elt_opcode (state, OP_FUNCALL);
2311 write_exp_elt_longcst (state, VEC_length (rust_op_ptr,
2312 *operation->right.params));
2313 write_exp_elt_longcst (state, OP_FUNCALL);
2318 gdb_assert (operation->left.op == NULL);
2319 convert_params_to_expression (state, *operation->right.params, top);
2320 write_exp_elt_opcode (state, OP_ARRAY);
2321 write_exp_elt_longcst (state, 0);
2322 write_exp_elt_longcst (state, VEC_length (rust_op_ptr,
2323 *operation->right.params) - 1);
2324 write_exp_elt_longcst (state, OP_ARRAY);
2329 struct block_symbol sym;
2330 const char *varname;
2332 if (operation->left.sval.ptr[0] == '$')
2334 write_dollar_variable (state, operation->left.sval);
2338 varname = convert_name (state, operation);
2339 sym = rust_lookup_symbol (varname, expression_context_block,
2341 if (sym.symbol != NULL)
2343 write_exp_elt_opcode (state, OP_VAR_VALUE);
2344 write_exp_elt_block (state, sym.block);
2345 write_exp_elt_sym (state, sym.symbol);
2346 write_exp_elt_opcode (state, OP_VAR_VALUE);
2352 type = rust_lookup_type (varname, expression_context_block);
2354 error (_("No symbol '%s' in current context"), varname);
2356 if (TYPE_CODE (type) == TYPE_CODE_STRUCT
2357 && TYPE_NFIELDS (type) == 0)
2359 /* A unit-like struct. */
2360 write_exp_elt_opcode (state, OP_AGGREGATE);
2361 write_exp_elt_type (state, type);
2362 write_exp_elt_longcst (state, 0);
2363 write_exp_elt_opcode (state, OP_AGGREGATE);
2365 else if (operation == top)
2367 write_exp_elt_opcode (state, OP_TYPE);
2368 write_exp_elt_type (state, type);
2369 write_exp_elt_opcode (state, OP_TYPE);
2380 struct set_field *init;
2381 VEC (set_field) *fields = *operation->right.field_inits;
2386 for (i = 0; VEC_iterate (set_field, fields, i, init); ++i)
2388 if (init->name.ptr != NULL)
2390 write_exp_elt_opcode (state, OP_NAME);
2391 write_exp_string (state, init->name);
2392 write_exp_elt_opcode (state, OP_NAME);
2396 convert_ast_to_expression (state, init->init, top);
2399 if (init->name.ptr == NULL)
2401 /* This is handled differently from Ada in our
2403 write_exp_elt_opcode (state, OP_OTHERS);
2407 name = convert_name (state, operation->left.op);
2408 type = rust_lookup_type (name, expression_context_block);
2410 error (_("Could not find type '%s'"), operation->left.sval.ptr);
2412 if (TYPE_CODE (type) != TYPE_CODE_STRUCT
2413 || rust_tuple_type_p (type)
2414 || rust_tuple_struct_type_p (type))
2415 error (_("Struct expression applied to non-struct type"));
2417 write_exp_elt_opcode (state, OP_AGGREGATE);
2418 write_exp_elt_type (state, type);
2419 write_exp_elt_longcst (state, length);
2420 write_exp_elt_opcode (state, OP_AGGREGATE);
2426 write_exp_elt_opcode (state, OP_STRING);
2427 write_exp_string (state, operation->left.sval);
2428 write_exp_elt_opcode (state, OP_STRING);
2434 enum range_type kind = BOTH_BOUND_DEFAULT;
2436 if (operation->left.op != NULL)
2438 convert_ast_to_expression (state, operation->left.op, top);
2439 kind = HIGH_BOUND_DEFAULT;
2441 if (operation->right.op != NULL)
2443 convert_ast_to_expression (state, operation->right.op, top);
2444 if (kind == BOTH_BOUND_DEFAULT)
2445 kind = LOW_BOUND_DEFAULT;
2448 gdb_assert (kind == HIGH_BOUND_DEFAULT);
2449 kind = NONE_BOUND_DEFAULT;
2452 write_exp_elt_opcode (state, OP_RANGE);
2453 write_exp_elt_longcst (state, kind);
2454 write_exp_elt_opcode (state, OP_RANGE);
2459 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_expression");
2465 /* The parser as exposed to gdb. */
2468 rust_parse (struct parser_state *state)
2471 struct cleanup *cleanup;
2473 obstack_init (&work_obstack);
2474 cleanup = make_cleanup_obstack_free (&work_obstack);
2478 result = rustyyparse ();
2480 if (!result || (parse_completion && rust_ast != NULL))
2482 const struct rust_op *ast = rust_ast;
2485 gdb_assert (ast != NULL);
2486 convert_ast_to_expression (state, ast, ast);
2489 do_cleanups (cleanup);
2493 /* The parser error handler. */
2496 rustyyerror (char *msg)
2498 const char *where = prev_lexptr ? prev_lexptr : lexptr;
2499 error (_("%s in expression, near `%s'."), (msg ? msg : "Error"), where);
2506 /* Initialize the lexer for testing. */
2509 rust_lex_test_init (const char *input)
2516 /* A test helper that lexes a string, expecting a single token. It
2517 returns the lexer data for this token. */
2520 rust_lex_test_one (const char *input, int expected)
2525 rust_lex_test_init (input);
2527 token = rustyylex ();
2528 SELF_CHECK (token == expected);
2529 result = rustyylval;
2533 token = rustyylex ();
2534 SELF_CHECK (token == 0);
2540 /* Test that INPUT lexes as the integer VALUE. */
2543 rust_lex_int_test (const char *input, int value, int kind)
2545 RUSTSTYPE result = rust_lex_test_one (input, kind);
2546 SELF_CHECK (result.typed_val_int.val == value);
2549 /* Test that INPUT throws an exception with text ERR. */
2552 rust_lex_exception_test (const char *input, const char *err)
2556 /* The "kind" doesn't matter. */
2557 rust_lex_test_one (input, DECIMAL_INTEGER);
2560 CATCH (except, RETURN_MASK_ERROR)
2562 SELF_CHECK (strcmp (except.message, err) == 0);
2567 /* Test that INPUT lexes as the identifier, string, or byte-string
2568 VALUE. KIND holds the expected token kind. */
2571 rust_lex_stringish_test (const char *input, const char *value, int kind)
2573 RUSTSTYPE result = rust_lex_test_one (input, kind);
2574 SELF_CHECK (result.sval.length == strlen (value));
2575 SELF_CHECK (strncmp (result.sval.ptr, value, result.sval.length) == 0);
2578 /* Helper to test that a string parses as a given token sequence. */
2581 rust_lex_test_sequence (const char *input, int len, const int expected[])
2588 for (i = 0; i < len; ++i)
2590 int token = rustyylex ();
2592 SELF_CHECK (token == expected[i]);
2596 /* Tests for an integer-parsing corner case. */
2599 rust_lex_test_trailing_dot (void)
2601 const int expected1[] = { DECIMAL_INTEGER, '.', IDENT, '(', ')', 0 };
2602 const int expected2[] = { INTEGER, '.', IDENT, '(', ')', 0 };
2603 const int expected3[] = { FLOAT, EQEQ, '(', ')', 0 };
2604 const int expected4[] = { DECIMAL_INTEGER, DOTDOT, DECIMAL_INTEGER, 0 };
2606 rust_lex_test_sequence ("23.g()", ARRAY_SIZE (expected1), expected1);
2607 rust_lex_test_sequence ("23_0.g()", ARRAY_SIZE (expected2), expected2);
2608 rust_lex_test_sequence ("23.==()", ARRAY_SIZE (expected3), expected3);
2609 rust_lex_test_sequence ("23..25", ARRAY_SIZE (expected4), expected4);
2612 /* Tests of completion. */
2615 rust_lex_test_completion (void)
2617 const int expected[] = { IDENT, '.', COMPLETE, 0 };
2619 parse_completion = 1;
2621 rust_lex_test_sequence ("something.wha", ARRAY_SIZE (expected), expected);
2622 rust_lex_test_sequence ("something.", ARRAY_SIZE (expected), expected);
2624 parse_completion = 0;
2627 /* Test pushback. */
2630 rust_lex_test_push_back (void)
2634 rust_lex_test_init (">>=");
2636 token = rustyylex ();
2637 SELF_CHECK (token == COMPOUND_ASSIGN);
2638 SELF_CHECK (rustyylval.opcode == BINOP_RSH);
2640 rust_push_back ('=');
2642 token = rustyylex ();
2643 SELF_CHECK (token == '=');
2645 token = rustyylex ();
2646 SELF_CHECK (token == 0);
2649 /* Unit test the lexer. */
2652 rust_lex_tests (void)
2656 obstack_init (&work_obstack);
2659 rust_lex_test_one ("", 0);
2660 rust_lex_test_one (" \t \n \r ", 0);
2661 rust_lex_test_one ("thread 23", 0);
2662 rust_lex_test_one ("task 23", 0);
2663 rust_lex_test_one ("th 104", 0);
2664 rust_lex_test_one ("ta 97", 0);
2666 rust_lex_int_test ("'z'", 'z', INTEGER);
2667 rust_lex_int_test ("'\\xff'", 0xff, INTEGER);
2668 rust_lex_int_test ("'\\u{1016f}'", 0x1016f, INTEGER);
2669 rust_lex_int_test ("b'z'", 'z', INTEGER);
2670 rust_lex_int_test ("b'\\xfe'", 0xfe, INTEGER);
2671 rust_lex_int_test ("b'\\xFE'", 0xfe, INTEGER);
2672 rust_lex_int_test ("b'\\xfE'", 0xfe, INTEGER);
2674 /* Test all escapes in both modes. */
2675 rust_lex_int_test ("'\\n'", '\n', INTEGER);
2676 rust_lex_int_test ("'\\r'", '\r', INTEGER);
2677 rust_lex_int_test ("'\\t'", '\t', INTEGER);
2678 rust_lex_int_test ("'\\\\'", '\\', INTEGER);
2679 rust_lex_int_test ("'\\0'", '\0', INTEGER);
2680 rust_lex_int_test ("'\\''", '\'', INTEGER);
2681 rust_lex_int_test ("'\\\"'", '"', INTEGER);
2683 rust_lex_int_test ("b'\\n'", '\n', INTEGER);
2684 rust_lex_int_test ("b'\\r'", '\r', INTEGER);
2685 rust_lex_int_test ("b'\\t'", '\t', INTEGER);
2686 rust_lex_int_test ("b'\\\\'", '\\', INTEGER);
2687 rust_lex_int_test ("b'\\0'", '\0', INTEGER);
2688 rust_lex_int_test ("b'\\''", '\'', INTEGER);
2689 rust_lex_int_test ("b'\\\"'", '"', INTEGER);
2691 rust_lex_exception_test ("'z", "Unterminated character literal");
2692 rust_lex_exception_test ("b'\\x0'", "Not enough hex digits seen");
2693 rust_lex_exception_test ("b'\\u{0}'", "Unicode escape in byte literal");
2694 rust_lex_exception_test ("'\\x0'", "Not enough hex digits seen");
2695 rust_lex_exception_test ("'\\u0'", "Missing '{' in Unicode escape");
2696 rust_lex_exception_test ("'\\u{0", "Missing '}' in Unicode escape");
2697 rust_lex_exception_test ("'\\u{0000007}", "Overlong hex escape");
2698 rust_lex_exception_test ("'\\u{}", "Not enough hex digits seen");
2699 rust_lex_exception_test ("'\\Q'", "Invalid escape \\Q in literal");
2700 rust_lex_exception_test ("b'\\Q'", "Invalid escape \\Q in literal");
2702 rust_lex_int_test ("23", 23, DECIMAL_INTEGER);
2703 rust_lex_int_test ("2_344__29", 234429, INTEGER);
2704 rust_lex_int_test ("0x1f", 0x1f, INTEGER);
2705 rust_lex_int_test ("23usize", 23, INTEGER);
2706 rust_lex_int_test ("23i32", 23, INTEGER);
2707 rust_lex_int_test ("0x1_f", 0x1f, INTEGER);
2708 rust_lex_int_test ("0b1_101011__", 0x6b, INTEGER);
2709 rust_lex_int_test ("0o001177i64", 639, INTEGER);
2711 rust_lex_test_trailing_dot ();
2713 rust_lex_test_one ("23.", FLOAT);
2714 rust_lex_test_one ("23.99f32", FLOAT);
2715 rust_lex_test_one ("23e7", FLOAT);
2716 rust_lex_test_one ("23E-7", FLOAT);
2717 rust_lex_test_one ("23e+7", FLOAT);
2718 rust_lex_test_one ("23.99e+7f64", FLOAT);
2719 rust_lex_test_one ("23.82f32", FLOAT);
2721 rust_lex_stringish_test ("hibob", "hibob", IDENT);
2722 rust_lex_stringish_test ("hibob__93", "hibob__93", IDENT);
2723 rust_lex_stringish_test ("thread", "thread", IDENT);
2725 rust_lex_stringish_test ("\"string\"", "string", STRING);
2726 rust_lex_stringish_test ("\"str\\ting\"", "str\ting", STRING);
2727 rust_lex_stringish_test ("\"str\\\"ing\"", "str\"ing", STRING);
2728 rust_lex_stringish_test ("r\"str\\ing\"", "str\\ing", STRING);
2729 rust_lex_stringish_test ("r#\"str\\ting\"#", "str\\ting", STRING);
2730 rust_lex_stringish_test ("r###\"str\\\"ing\"###", "str\\\"ing", STRING);
2732 rust_lex_stringish_test ("b\"string\"", "string", BYTESTRING);
2733 rust_lex_stringish_test ("b\"\x73tring\"", "string", BYTESTRING);
2734 rust_lex_stringish_test ("b\"str\\\"ing\"", "str\"ing", BYTESTRING);
2735 rust_lex_stringish_test ("br####\"\\x73tring\"####", "\\x73tring",
2738 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
2739 rust_lex_test_one (identifier_tokens[i].name, identifier_tokens[i].value);
2741 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
2742 rust_lex_test_one (operator_tokens[i].name, operator_tokens[i].value);
2744 rust_lex_test_completion ();
2745 rust_lex_test_push_back ();
2747 obstack_free (&work_obstack, NULL);
2751 #endif /* GDB_SELF_TEST */
2754 _initialize_rust_exp (void)
2756 int code = regcomp (&number_regex, number_regex_text, REG_EXTENDED);
2757 /* If the regular expression was incorrect, it was a programming
2759 gdb_assert (code == 0);
2762 register_self_test (rust_lex_tests);