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
279 %token <voidval> KW_SIZEOF
281 /* Operator tokens. */
282 %token <voidval> DOTDOT
283 %token <voidval> OROR
284 %token <voidval> ANDAND
285 %token <voidval> EQEQ
286 %token <voidval> NOTEQ
287 %token <voidval> LTEQ
288 %token <voidval> GTEQ
289 %token <voidval> LSH RSH
290 %token <voidval> COLONCOLON
291 %token <voidval> ARROW
294 %type <op> path_for_expr
295 %type <op> identifier_path_for_expr
296 %type <op> path_for_type
297 %type <op> identifier_path_for_type
298 %type <op> just_identifiers_for_type
300 %type <params> maybe_type_list
301 %type <params> type_list
303 %type <depth> super_path
307 %type <op> field_expr
310 %type <op> binop_expr
311 %type <op> binop_expr_expr
312 %type <op> type_cast_expr
313 %type <op> assignment_expr
314 %type <op> compound_assignment_expr
315 %type <op> paren_expr
318 %type <op> tuple_expr
320 %type <op> struct_expr
321 %type <op> array_expr
322 %type <op> range_expr
324 %type <params> expr_list
325 %type <params> maybe_expr_list
326 %type <params> paren_expr_list
328 %type <field_inits> struct_expr_list
329 %type <one_field_init> struct_expr_tail
333 %right '=' COMPOUND_ASSIGN
336 %nonassoc EQEQ NOTEQ '<' '>' LTEQ GTEQ
344 /* These could be %precedence in Bison, but that isn't a yacc
355 /* If we are completing and see a valid parse,
356 rust_ast will already have been set. */
357 if (rust_ast == NULL)
362 /* Note that the Rust grammar includes a method_call_expr, but we
363 handle this differently, to avoid a shift/reduce conflict with
375 | unop_expr /* Must precede call_expr because of ambiguity with sizeof. */
382 '(' expr ',' maybe_expr_list ')'
384 VEC_safe_insert (rust_op_ptr, *$4, 0, $2);
385 error (_("Tuple expressions not supported yet"));
392 struct typed_val_int val;
395 = language_lookup_primitive_type (parse_language (pstate),
396 parse_gdbarch (pstate),
399 $$ = ast_literal (val);
403 /* To avoid a shift/reduce conflict with call_expr, we don't handle
404 tuple struct expressions here, but instead when examining the
407 path_for_expr '{' struct_expr_list '}'
408 { $$ = ast_struct ($1, $3); }
435 VEC (set_field) **result
436 = OBSTACK_ZALLOC (&work_obstack, VEC (set_field) *);
441 VEC (set_field) **result
442 = OBSTACK_ZALLOC (&work_obstack, VEC (set_field) *);
444 make_cleanup (VEC_cleanup (set_field), result);
445 VEC_safe_push (set_field, *result, &$1);
449 | IDENT ':' expr ',' struct_expr_list
455 VEC_safe_push (set_field, *$5, &sf);
461 '[' KW_MUT expr_list ']'
462 { $$ = ast_call_ish (OP_ARRAY, NULL, $3); }
464 { $$ = ast_call_ish (OP_ARRAY, NULL, $2); }
465 | '[' KW_MUT expr ';' expr ']'
466 { $$ = ast_operation (OP_RUST_ARRAY, $3, $5); }
467 | '[' expr ';' expr ']'
468 { $$ = ast_operation (OP_RUST_ARRAY, $2, $4); }
473 { $$ = ast_range ($1, NULL); }
475 { $$ = ast_range ($1, $3); }
477 { $$ = ast_range (NULL, $2); }
479 { $$ = ast_range (NULL, NULL); }
484 { $$ = ast_literal ($1); }
486 { $$ = ast_literal ($1); }
488 { $$ = ast_dliteral ($1); }
491 const struct rust_op *str = ast_string ($1);
492 VEC (set_field) **fields;
493 struct set_field field;
494 struct typed_val_int val;
497 fields = OBSTACK_ZALLOC (&work_obstack, VEC (set_field) *);
498 make_cleanup (VEC_cleanup (set_field), fields);
500 /* Wrap the raw string in the &str struct. */
501 field.name.ptr = "data_ptr";
502 field.name.length = strlen (field.name.ptr);
503 field.init = ast_unary (UNOP_ADDR, ast_string ($1));
504 VEC_safe_push (set_field, *fields, &field);
506 val.type = rust_type ("usize");
509 field.name.ptr = "length";
510 field.name.length = strlen (field.name.ptr);
511 field.init = ast_literal (val);
512 VEC_safe_push (set_field, *fields, &field);
515 token.length = strlen (token.ptr);
516 $$ = ast_struct (ast_path (token, NULL), fields);
519 { $$ = ast_string ($1); }
522 struct typed_val_int val;
524 val.type = language_bool_type (parse_language (pstate),
525 parse_gdbarch (pstate));
527 $$ = ast_literal (val);
531 struct typed_val_int val;
533 val.type = language_bool_type (parse_language (pstate),
534 parse_gdbarch (pstate));
536 $$ = ast_literal (val);
542 { $$ = ast_structop ($1, $3.ptr, 0); }
545 $$ = ast_structop ($1, $3.ptr, 1);
548 | expr '.' DECIMAL_INTEGER
549 { $$ = ast_structop_anonymous ($1, $3); }
554 { $$ = ast_operation (BINOP_SUBSCRIPT, $1, $3); }
559 { $$ = ast_unary (UNOP_PLUS, $2); }
561 | '-' expr %prec UNARY
562 { $$ = ast_unary (UNOP_NEG, $2); }
564 | '!' expr %prec UNARY
566 /* Note that we provide a Rust-specific evaluator
567 override for UNOP_COMPLEMENT, so it can do the
568 right thing for both bool and integral
570 $$ = ast_unary (UNOP_COMPLEMENT, $2);
573 | '*' expr %prec UNARY
574 { $$ = ast_unary (UNOP_IND, $2); }
576 | '&' expr %prec UNARY
577 { $$ = ast_unary (UNOP_ADDR, $2); }
579 | '&' KW_MUT expr %prec UNARY
580 { $$ = ast_unary (UNOP_ADDR, $3); }
581 | KW_SIZEOF '(' expr ')' %prec UNARY
582 { $$ = ast_unary (UNOP_SIZEOF, $3); }
589 | compound_assignment_expr
594 { $$ = ast_operation (BINOP_MUL, $1, $3); }
597 { $$ = ast_operation (BINOP_REPEAT, $1, $3); }
600 { $$ = ast_operation (BINOP_DIV, $1, $3); }
603 { $$ = ast_operation (BINOP_REM, $1, $3); }
606 { $$ = ast_operation (BINOP_LESS, $1, $3); }
609 { $$ = ast_operation (BINOP_GTR, $1, $3); }
612 { $$ = ast_operation (BINOP_BITWISE_AND, $1, $3); }
615 { $$ = ast_operation (BINOP_BITWISE_IOR, $1, $3); }
618 { $$ = ast_operation (BINOP_BITWISE_XOR, $1, $3); }
621 { $$ = ast_operation (BINOP_ADD, $1, $3); }
624 { $$ = ast_operation (BINOP_SUB, $1, $3); }
627 { $$ = ast_operation (BINOP_LOGICAL_OR, $1, $3); }
630 { $$ = ast_operation (BINOP_LOGICAL_AND, $1, $3); }
633 { $$ = ast_operation (BINOP_EQUAL, $1, $3); }
636 { $$ = ast_operation (BINOP_NOTEQUAL, $1, $3); }
639 { $$ = ast_operation (BINOP_LEQ, $1, $3); }
642 { $$ = ast_operation (BINOP_GEQ, $1, $3); }
645 { $$ = ast_operation (BINOP_LSH, $1, $3); }
648 { $$ = ast_operation (BINOP_RSH, $1, $3); }
653 { $$ = ast_cast ($1, $3); }
658 { $$ = ast_operation (BINOP_ASSIGN, $1, $3); }
661 compound_assignment_expr:
662 expr COMPOUND_ASSIGN expr
663 { $$ = ast_compound_assignment ($2, $1, $3); }
675 $$ = OBSTACK_ZALLOC (&work_obstack, VEC (rust_op_ptr) *);
676 make_cleanup (VEC_cleanup (rust_op_ptr), $$);
677 VEC_safe_push (rust_op_ptr, *$$, $1);
681 VEC_safe_push (rust_op_ptr, *$1, $3);
689 /* The result can't be NULL. */
690 $$ = OBSTACK_ZALLOC (&work_obstack, VEC (rust_op_ptr) *);
691 make_cleanup (VEC_cleanup (rust_op_ptr), $$);
706 { $$ = ast_call_ish (OP_FUNCALL, $1, $2); }
717 | super_path KW_SUPER COLONCOLON
725 { $$ = ast_path ($1, NULL); }
727 { $$ = ast_path (make_stoken ("self"), NULL); }
731 identifier_path_for_expr
732 | KW_SELF COLONCOLON identifier_path_for_expr
733 { $$ = super_name ($3, 0); }
734 | maybe_self_path super_path identifier_path_for_expr
735 { $$ = super_name ($3, $2); }
736 | COLONCOLON identifier_path_for_expr
737 { $$ = crate_name ($2); }
738 | KW_EXTERN identifier_path_for_expr
740 /* This is a gdb extension to make it possible to
741 refer to items in other crates. It just bypasses
742 adding the current crate to the front of the
744 $$ = ast_path (rust_concat3 ("::", $2->left.sval.ptr, NULL),
749 identifier_path_for_expr:
751 { $$ = ast_path ($1, NULL); }
752 | identifier_path_for_expr COLONCOLON IDENT
754 $$ = ast_path (rust_concat3 ($1->left.sval.ptr, "::",
758 | identifier_path_for_expr COLONCOLON '<' type_list '>'
759 { $$ = ast_path ($1->left.sval, $4); }
760 | identifier_path_for_expr COLONCOLON '<' type_list RSH
762 $$ = ast_path ($1->left.sval, $4);
763 rust_push_back ('>');
768 identifier_path_for_type
769 | KW_SELF COLONCOLON identifier_path_for_type
770 { $$ = super_name ($3, 0); }
771 | maybe_self_path super_path identifier_path_for_type
772 { $$ = super_name ($3, $2); }
773 | COLONCOLON identifier_path_for_type
774 { $$ = crate_name ($2); }
775 | KW_EXTERN identifier_path_for_type
777 /* This is a gdb extension to make it possible to
778 refer to items in other crates. It just bypasses
779 adding the current crate to the front of the
781 $$ = ast_path (rust_concat3 ("::", $2->left.sval.ptr, NULL),
786 just_identifiers_for_type:
788 { $$ = ast_path ($1, NULL); }
789 | just_identifiers_for_type COLONCOLON IDENT
791 $$ = ast_path (rust_concat3 ($1->left.sval.ptr, "::",
797 identifier_path_for_type:
798 just_identifiers_for_type
799 | just_identifiers_for_type '<' type_list '>'
800 { $$ = ast_path ($1->left.sval, $3); }
801 | just_identifiers_for_type '<' type_list RSH
803 $$ = ast_path ($1->left.sval, $3);
804 rust_push_back ('>');
810 | '[' type ';' INTEGER ']'
811 { $$ = ast_array_type ($2, $4); }
812 | '[' type ';' DECIMAL_INTEGER ']'
813 { $$ = ast_array_type ($2, $4); }
815 { $$ = ast_slice_type ($3); }
817 { $$ = ast_reference_type ($2); }
819 { $$ = ast_pointer_type ($3, 1); }
821 { $$ = ast_pointer_type ($3, 0); }
822 | KW_FN '(' maybe_type_list ')' ARROW type
823 { $$ = ast_function_type ($6, $3); }
824 | '(' maybe_type_list ')'
825 { $$ = ast_tuple_type ($2); }
838 VEC (rust_op_ptr) **result
839 = OBSTACK_ZALLOC (&work_obstack, VEC (rust_op_ptr) *);
841 make_cleanup (VEC_cleanup (rust_op_ptr), result);
842 VEC_safe_push (rust_op_ptr, *result, $1);
847 VEC_safe_push (rust_op_ptr, *$1, $3);
854 /* A struct of this type is used to describe a token. */
860 enum exp_opcode opcode;
863 /* Identifier tokens. */
865 static const struct token_info identifier_tokens[] =
867 { "as", KW_AS, OP_NULL },
868 { "false", KW_FALSE, OP_NULL },
869 { "if", 0, OP_NULL },
870 { "mut", KW_MUT, OP_NULL },
871 { "const", KW_CONST, OP_NULL },
872 { "self", KW_SELF, OP_NULL },
873 { "super", KW_SUPER, OP_NULL },
874 { "true", KW_TRUE, OP_NULL },
875 { "extern", KW_EXTERN, OP_NULL },
876 { "fn", KW_FN, OP_NULL },
877 { "sizeof", KW_SIZEOF, OP_NULL },
880 /* Operator tokens, sorted longest first. */
882 static const struct token_info operator_tokens[] =
884 { ">>=", COMPOUND_ASSIGN, BINOP_RSH },
885 { "<<=", COMPOUND_ASSIGN, BINOP_LSH },
887 { "<<", LSH, OP_NULL },
888 { ">>", RSH, OP_NULL },
889 { "&&", ANDAND, OP_NULL },
890 { "||", OROR, OP_NULL },
891 { "==", EQEQ, OP_NULL },
892 { "!=", NOTEQ, OP_NULL },
893 { "<=", LTEQ, OP_NULL },
894 { ">=", GTEQ, OP_NULL },
895 { "+=", COMPOUND_ASSIGN, BINOP_ADD },
896 { "-=", COMPOUND_ASSIGN, BINOP_SUB },
897 { "*=", COMPOUND_ASSIGN, BINOP_MUL },
898 { "/=", COMPOUND_ASSIGN, BINOP_DIV },
899 { "%=", COMPOUND_ASSIGN, BINOP_REM },
900 { "&=", COMPOUND_ASSIGN, BINOP_BITWISE_AND },
901 { "|=", COMPOUND_ASSIGN, BINOP_BITWISE_IOR },
902 { "^=", COMPOUND_ASSIGN, BINOP_BITWISE_XOR },
904 { "::", COLONCOLON, OP_NULL },
905 { "..", DOTDOT, OP_NULL },
906 { "->", ARROW, OP_NULL }
909 /* Helper function to copy to the name obstack. */
912 rust_copy_name (const char *name, int len)
914 return (const char *) obstack_copy0 (&work_obstack, name, len);
917 /* Helper function to make an stoken from a C string. */
920 make_stoken (const char *p)
922 struct stoken result;
925 result.length = strlen (result.ptr);
929 /* Helper function to concatenate three strings on the name
933 rust_concat3 (const char *s1, const char *s2, const char *s3)
935 return make_stoken (obconcat (&work_obstack, s1, s2, s3, (char *) NULL));
938 /* Return an AST node referring to NAME, but relative to the crate's
941 static const struct rust_op *
942 crate_name (const struct rust_op *name)
944 char *crate = rust_crate_for_block (expression_context_block);
945 struct stoken result;
947 gdb_assert (name->opcode == OP_VAR_VALUE);
950 error (_("Could not find crate for current location"));
951 result = make_stoken (obconcat (&work_obstack, "::", crate, "::",
952 name->left.sval.ptr, (char *) NULL));
955 return ast_path (result, name->right.params);
958 /* Create an AST node referring to a "super::" qualified name. IDENT
959 is the base name and N_SUPERS is how many "super::"s were
960 provided. N_SUPERS can be zero. */
962 static const struct rust_op *
963 super_name (const struct rust_op *ident, unsigned int n_supers)
965 const char *scope = block_scope (expression_context_block);
968 gdb_assert (ident->opcode == OP_VAR_VALUE);
970 if (scope[0] == '\0')
971 error (_("Couldn't find namespace scope for self::"));
977 std::vector<int> offsets;
978 unsigned int current_len;
980 current_len = cp_find_first_component (scope);
981 while (scope[current_len] != '\0')
983 offsets.push_back (current_len);
984 gdb_assert (scope[current_len] == ':');
987 current_len += cp_find_first_component (scope
991 len = offsets.size ();
993 error (_("Too many super:: uses from '%s'"), scope);
995 offset = offsets[len - n_supers];
998 offset = strlen (scope);
1000 obstack_grow (&work_obstack, "::", 2);
1001 obstack_grow (&work_obstack, scope, offset);
1002 obstack_grow (&work_obstack, "::", 2);
1003 obstack_grow0 (&work_obstack, ident->left.sval.ptr, ident->left.sval.length);
1005 return ast_path (make_stoken ((const char *) obstack_finish (&work_obstack)),
1006 ident->right.params);
1009 /* A helper that updates innermost_block as appropriate. */
1012 update_innermost_block (struct block_symbol sym)
1014 if (symbol_read_needs_frame (sym.symbol)
1015 && (innermost_block == NULL
1016 || contained_in (sym.block, innermost_block)))
1017 innermost_block = sym.block;
1020 /* A helper to look up a Rust type, or fail. This only works for
1021 types defined by rust_language_arch_info. */
1023 static struct type *
1024 rust_type (const char *name)
1028 /* When unit testing, we don't bother checking the types, so avoid a
1029 possibly-failing lookup here. */
1033 type = language_lookup_primitive_type (parse_language (pstate),
1034 parse_gdbarch (pstate),
1037 error (_("Could not find Rust type %s"), name);
1041 /* Lex a hex number with at least MIN digits and at most MAX
1045 lex_hex (int min, int max)
1047 uint32_t result = 0;
1049 /* We only want to stop at MAX if we're lexing a byte escape. */
1050 int check_max = min == max;
1052 while ((check_max ? len <= max : 1)
1053 && ((lexptr[0] >= 'a' && lexptr[0] <= 'f')
1054 || (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1055 || (lexptr[0] >= '0' && lexptr[0] <= '9')))
1058 if (lexptr[0] >= 'a' && lexptr[0] <= 'f')
1059 result = result + 10 + lexptr[0] - 'a';
1060 else if (lexptr[0] >= 'A' && lexptr[0] <= 'F')
1061 result = result + 10 + lexptr[0] - 'A';
1063 result = result + lexptr[0] - '0';
1069 error (_("Not enough hex digits seen"));
1072 gdb_assert (min != max);
1073 error (_("Overlong hex escape"));
1079 /* Lex an escape. IS_BYTE is true if we're lexing a byte escape;
1080 otherwise we're lexing a character escape. */
1083 lex_escape (int is_byte)
1087 gdb_assert (lexptr[0] == '\\');
1093 result = lex_hex (2, 2);
1098 error (_("Unicode escape in byte literal"));
1100 if (lexptr[0] != '{')
1101 error (_("Missing '{' in Unicode escape"));
1103 result = lex_hex (1, 6);
1104 /* Could do range checks here. */
1105 if (lexptr[0] != '}')
1106 error (_("Missing '}' in Unicode escape"));
1140 error (_("Invalid escape \\%c in literal"), lexptr[0]);
1146 /* Lex a character constant. */
1149 lex_character (void)
1154 if (lexptr[0] == 'b')
1159 gdb_assert (lexptr[0] == '\'');
1161 /* This should handle UTF-8 here. */
1162 if (lexptr[0] == '\\')
1163 value = lex_escape (is_byte);
1166 value = lexptr[0] & 0xff;
1170 if (lexptr[0] != '\'')
1171 error (_("Unterminated character literal"));
1174 rustyylval.typed_val_int.val = value;
1175 rustyylval.typed_val_int.type = rust_type (is_byte ? "u8" : "char");
1180 /* Return the offset of the double quote if STR looks like the start
1181 of a raw string, or 0 if STR does not start a raw string. */
1184 starts_raw_string (const char *str)
1186 const char *save = str;
1191 while (str[0] == '#')
1198 /* Return true if STR looks like the end of a raw string that had N
1199 hashes at the start. */
1202 ends_raw_string (const char *str, int n)
1206 gdb_assert (str[0] == '"');
1207 for (i = 0; i < n; ++i)
1208 if (str[i + 1] != '#')
1213 /* Lex a string constant. */
1218 int is_byte = lexptr[0] == 'b';
1220 int len_in_chars = 0;
1224 raw_length = starts_raw_string (lexptr);
1225 lexptr += raw_length;
1226 gdb_assert (lexptr[0] == '"');
1235 if (lexptr[0] == '"' && ends_raw_string (lexptr, raw_length - 1))
1237 /* Exit with lexptr pointing after the final "#". */
1238 lexptr += raw_length;
1241 else if (lexptr[0] == '\0')
1242 error (_("Unexpected EOF in string"));
1244 value = lexptr[0] & 0xff;
1245 if (is_byte && value > 127)
1246 error (_("Non-ASCII value in raw byte string"));
1247 obstack_1grow (&work_obstack, value);
1251 else if (lexptr[0] == '"')
1253 /* Make sure to skip the quote. */
1257 else if (lexptr[0] == '\\')
1259 value = lex_escape (is_byte);
1262 obstack_1grow (&work_obstack, value);
1264 convert_between_encodings ("UTF-32", "UTF-8", (gdb_byte *) &value,
1265 sizeof (value), sizeof (value),
1266 &work_obstack, translit_none);
1268 else if (lexptr[0] == '\0')
1269 error (_("Unexpected EOF in string"));
1272 value = lexptr[0] & 0xff;
1273 if (is_byte && value > 127)
1274 error (_("Non-ASCII value in byte string"));
1275 obstack_1grow (&work_obstack, value);
1280 rustyylval.sval.length = obstack_object_size (&work_obstack);
1281 rustyylval.sval.ptr = (const char *) obstack_finish (&work_obstack);
1282 return is_byte ? BYTESTRING : STRING;
1285 /* Return true if STRING starts with whitespace followed by a digit. */
1288 space_then_number (const char *string)
1290 const char *p = string;
1292 while (p[0] == ' ' || p[0] == '\t')
1297 return *p >= '0' && *p <= '9';
1300 /* Return true if C can start an identifier. */
1303 rust_identifier_start_p (char c)
1305 return ((c >= 'a' && c <= 'z')
1306 || (c >= 'A' && c <= 'Z')
1311 /* Lex an identifier. */
1314 lex_identifier (void)
1316 const char *start = lexptr;
1317 unsigned int length;
1318 const struct token_info *token;
1320 int is_gdb_var = lexptr[0] == '$';
1322 gdb_assert (rust_identifier_start_p (lexptr[0]));
1326 /* For the time being this doesn't handle Unicode rules. Non-ASCII
1327 identifiers are gated anyway. */
1328 while ((lexptr[0] >= 'a' && lexptr[0] <= 'z')
1329 || (lexptr[0] >= 'A' && lexptr[0] <= 'Z')
1331 || (is_gdb_var && lexptr[0] == '$')
1332 || (lexptr[0] >= '0' && lexptr[0] <= '9'))
1336 length = lexptr - start;
1338 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
1340 if (length == strlen (identifier_tokens[i].name)
1341 && strncmp (identifier_tokens[i].name, start, length) == 0)
1343 token = &identifier_tokens[i];
1350 if (token->value == 0)
1352 /* Leave the terminating token alone. */
1357 else if (token == NULL
1358 && (strncmp (start, "thread", length) == 0
1359 || strncmp (start, "task", length) == 0)
1360 && space_then_number (lexptr))
1362 /* "task" or "thread" followed by a number terminates the
1363 parse, per gdb rules. */
1368 if (token == NULL || (parse_completion && lexptr[0] == '\0'))
1369 rustyylval.sval = make_stoken (rust_copy_name (start, length));
1371 if (parse_completion && lexptr[0] == '\0')
1373 /* Prevent rustyylex from returning two COMPLETE tokens. */
1374 prev_lexptr = lexptr;
1379 return token->value;
1385 /* Lex an operator. */
1390 const struct token_info *token = NULL;
1393 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
1395 if (strncmp (operator_tokens[i].name, lexptr,
1396 strlen (operator_tokens[i].name)) == 0)
1398 lexptr += strlen (operator_tokens[i].name);
1399 token = &operator_tokens[i];
1406 rustyylval.opcode = token->opcode;
1407 return token->value;
1418 regmatch_t subexps[NUM_SUBEXPRESSIONS];
1421 int could_be_decimal = 1;
1422 int implicit_i32 = 0;
1423 const char *type_name = NULL;
1426 int type_index = -1;
1429 match = regexec (&number_regex, lexptr, ARRAY_SIZE (subexps), subexps, 0);
1430 /* Failure means the regexp is broken. */
1431 gdb_assert (match == 0);
1433 if (subexps[INT_TEXT].rm_so != -1)
1435 /* Integer part matched. */
1437 end_index = subexps[INT_TEXT].rm_eo;
1438 if (subexps[INT_TYPE].rm_so == -1)
1445 type_index = INT_TYPE;
1446 could_be_decimal = 0;
1449 else if (subexps[FLOAT_TYPE1].rm_so != -1)
1451 /* Found floating point type suffix. */
1452 end_index = subexps[FLOAT_TYPE1].rm_so;
1453 type_index = FLOAT_TYPE1;
1455 else if (subexps[FLOAT_TYPE2].rm_so != -1)
1457 /* Found floating point type suffix. */
1458 end_index = subexps[FLOAT_TYPE2].rm_so;
1459 type_index = FLOAT_TYPE2;
1463 /* Any other floating point match. */
1464 end_index = subexps[0].rm_eo;
1468 /* We need a special case if the final character is ".". In this
1469 case we might need to parse an integer. For example, "23.f()" is
1470 a request for a trait method call, not a syntax error involving
1471 the floating point number "23.". */
1472 gdb_assert (subexps[0].rm_eo > 0);
1473 if (lexptr[subexps[0].rm_eo - 1] == '.')
1475 const char *next = skip_spaces_const (&lexptr[subexps[0].rm_eo]);
1477 if (rust_identifier_start_p (*next) || *next == '.')
1481 end_index = subexps[0].rm_eo;
1483 could_be_decimal = 1;
1488 /* Compute the type name if we haven't already. */
1489 std::string type_name_holder;
1490 if (type_name == NULL)
1492 gdb_assert (type_index != -1);
1493 type_name_holder = std::string (lexptr + subexps[type_index].rm_so,
1494 (subexps[type_index].rm_eo
1495 - subexps[type_index].rm_so));
1496 type_name = type_name_holder.c_str ();
1499 /* Look up the type. */
1500 type = rust_type (type_name);
1502 /* Copy the text of the number and remove the "_"s. */
1504 for (i = 0; i < end_index && lexptr[i]; ++i)
1506 if (lexptr[i] == '_')
1507 could_be_decimal = 0;
1509 number.push_back (lexptr[i]);
1512 /* Advance past the match. */
1513 lexptr += subexps[0].rm_eo;
1515 /* Parse the number. */
1522 if (number[0] == '0')
1524 if (number[1] == 'x')
1526 else if (number[1] == 'o')
1528 else if (number[1] == 'b')
1533 could_be_decimal = 0;
1537 value = strtoul (number.c_str () + offset, NULL, radix);
1538 if (implicit_i32 && value >= ((uint64_t) 1) << 31)
1539 type = rust_type ("i64");
1541 rustyylval.typed_val_int.val = value;
1542 rustyylval.typed_val_int.type = type;
1546 rustyylval.typed_val_float.dval = strtod (number.c_str (), NULL);
1547 rustyylval.typed_val_float.type = type;
1550 return is_integer ? (could_be_decimal ? DECIMAL_INTEGER : INTEGER) : FLOAT;
1558 /* Skip all leading whitespace. */
1559 while (lexptr[0] == ' ' || lexptr[0] == '\t' || lexptr[0] == '\r'
1560 || lexptr[0] == '\n')
1563 /* If we hit EOF and we're completing, then return COMPLETE -- maybe
1564 we're completing an empty string at the end of a field_expr.
1565 But, we don't want to return two COMPLETE tokens in a row. */
1566 if (lexptr[0] == '\0' && lexptr == prev_lexptr)
1568 prev_lexptr = lexptr;
1569 if (lexptr[0] == '\0')
1571 if (parse_completion)
1573 rustyylval.sval = make_stoken ("");
1579 if (lexptr[0] >= '0' && lexptr[0] <= '9')
1580 return lex_number ();
1581 else if (lexptr[0] == 'b' && lexptr[1] == '\'')
1582 return lex_character ();
1583 else if (lexptr[0] == 'b' && lexptr[1] == '"')
1584 return lex_string ();
1585 else if (lexptr[0] == 'b' && starts_raw_string (lexptr + 1))
1586 return lex_string ();
1587 else if (starts_raw_string (lexptr))
1588 return lex_string ();
1589 else if (rust_identifier_start_p (lexptr[0]))
1590 return lex_identifier ();
1591 else if (lexptr[0] == '"')
1592 return lex_string ();
1593 else if (lexptr[0] == '\'')
1594 return lex_character ();
1595 else if (lexptr[0] == '}' || lexptr[0] == ']')
1597 /* Falls through to lex_operator. */
1600 else if (lexptr[0] == '(' || lexptr[0] == '{')
1602 /* Falls through to lex_operator. */
1605 else if (lexptr[0] == ',' && comma_terminates && paren_depth == 0)
1608 return lex_operator ();
1611 /* Push back a single character to be re-lexed. */
1614 rust_push_back (char c)
1616 /* Can't be called before any lexing. */
1617 gdb_assert (prev_lexptr != NULL);
1620 gdb_assert (*lexptr == c);
1625 /* Make an arbitrary operation and fill in the fields. */
1627 static const struct rust_op *
1628 ast_operation (enum exp_opcode opcode, const struct rust_op *left,
1629 const struct rust_op *right)
1631 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1633 result->opcode = opcode;
1634 result->left.op = left;
1635 result->right.op = right;
1640 /* Make a compound assignment operation. */
1642 static const struct rust_op *
1643 ast_compound_assignment (enum exp_opcode opcode, const struct rust_op *left,
1644 const struct rust_op *right)
1646 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1648 result->opcode = opcode;
1649 result->compound_assignment = 1;
1650 result->left.op = left;
1651 result->right.op = right;
1656 /* Make a typed integer literal operation. */
1658 static const struct rust_op *
1659 ast_literal (struct typed_val_int val)
1661 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1663 result->opcode = OP_LONG;
1664 result->left.typed_val_int = val;
1669 /* Make a typed floating point literal operation. */
1671 static const struct rust_op *
1672 ast_dliteral (struct typed_val_float val)
1674 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1676 result->opcode = OP_DOUBLE;
1677 result->left.typed_val_float = val;
1682 /* Make a unary operation. */
1684 static const struct rust_op *
1685 ast_unary (enum exp_opcode opcode, const struct rust_op *expr)
1687 return ast_operation (opcode, expr, NULL);
1690 /* Make a cast operation. */
1692 static const struct rust_op *
1693 ast_cast (const struct rust_op *expr, const struct rust_op *type)
1695 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1697 result->opcode = UNOP_CAST;
1698 result->left.op = expr;
1699 result->right.op = type;
1704 /* Make a call-like operation. This is nominally a function call, but
1705 when lowering we may discover that it actually represents the
1706 creation of a tuple struct. */
1708 static const struct rust_op *
1709 ast_call_ish (enum exp_opcode opcode, const struct rust_op *expr,
1710 VEC (rust_op_ptr) **params)
1712 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1714 result->opcode = opcode;
1715 result->left.op = expr;
1716 result->right.params = params;
1721 /* Make a structure creation operation. */
1723 static const struct rust_op *
1724 ast_struct (const struct rust_op *name, VEC (set_field) **fields)
1726 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1728 result->opcode = OP_AGGREGATE;
1729 result->left.op = name;
1730 result->right.field_inits = fields;
1735 /* Make an identifier path. */
1737 static const struct rust_op *
1738 ast_path (struct stoken path, VEC (rust_op_ptr) **params)
1740 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1742 result->opcode = OP_VAR_VALUE;
1743 result->left.sval = path;
1744 result->right.params = params;
1749 /* Make a string constant operation. */
1751 static const struct rust_op *
1752 ast_string (struct stoken str)
1754 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1756 result->opcode = OP_STRING;
1757 result->left.sval = str;
1762 /* Make a field expression. */
1764 static const struct rust_op *
1765 ast_structop (const struct rust_op *left, const char *name, int completing)
1767 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1769 result->opcode = STRUCTOP_STRUCT;
1770 result->completing = completing;
1771 result->left.op = left;
1772 result->right.sval = make_stoken (name);
1777 /* Make an anonymous struct operation, like 'x.0'. */
1779 static const struct rust_op *
1780 ast_structop_anonymous (const struct rust_op *left,
1781 struct typed_val_int number)
1783 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1785 result->opcode = STRUCTOP_ANONYMOUS;
1786 result->left.op = left;
1787 result->right.typed_val_int = number;
1792 /* Make a range operation. */
1794 static const struct rust_op *
1795 ast_range (const struct rust_op *lhs, const struct rust_op *rhs)
1797 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1799 result->opcode = OP_RANGE;
1800 result->left.op = lhs;
1801 result->right.op = rhs;
1806 /* A helper function to make a type-related AST node. */
1808 static struct rust_op *
1809 ast_basic_type (enum type_code typecode)
1811 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1813 result->opcode = OP_TYPE;
1814 result->typecode = typecode;
1818 /* Create an AST node describing an array type. */
1820 static const struct rust_op *
1821 ast_array_type (const struct rust_op *lhs, struct typed_val_int val)
1823 struct rust_op *result = ast_basic_type (TYPE_CODE_ARRAY);
1825 result->left.op = lhs;
1826 result->right.typed_val_int = val;
1830 /* Create an AST node describing a reference type. */
1832 static const struct rust_op *
1833 ast_slice_type (const struct rust_op *type)
1835 /* Use TYPE_CODE_COMPLEX just because it is handy. */
1836 struct rust_op *result = ast_basic_type (TYPE_CODE_COMPLEX);
1838 result->left.op = type;
1842 /* Create an AST node describing a reference type. */
1844 static const struct rust_op *
1845 ast_reference_type (const struct rust_op *type)
1847 struct rust_op *result = ast_basic_type (TYPE_CODE_REF);
1849 result->left.op = type;
1853 /* Create an AST node describing a pointer type. */
1855 static const struct rust_op *
1856 ast_pointer_type (const struct rust_op *type, int is_mut)
1858 struct rust_op *result = ast_basic_type (TYPE_CODE_PTR);
1860 result->left.op = type;
1861 /* For the time being we ignore is_mut. */
1865 /* Create an AST node describing a function type. */
1867 static const struct rust_op *
1868 ast_function_type (const struct rust_op *rtype, VEC (rust_op_ptr) **params)
1870 struct rust_op *result = ast_basic_type (TYPE_CODE_FUNC);
1872 result->left.op = rtype;
1873 result->right.params = params;
1877 /* Create an AST node describing a tuple type. */
1879 static const struct rust_op *
1880 ast_tuple_type (VEC (rust_op_ptr) **params)
1882 struct rust_op *result = ast_basic_type (TYPE_CODE_STRUCT);
1884 result->left.params = params;
1888 /* A helper to appropriately munge NAME and BLOCK depending on the
1889 presence of a leading "::". */
1892 munge_name_and_block (const char **name, const struct block **block)
1894 /* If it is a global reference, skip the current block in favor of
1895 the static block. */
1896 if (strncmp (*name, "::", 2) == 0)
1899 *block = block_static_block (*block);
1903 /* Like lookup_symbol, but handles Rust namespace conventions, and
1904 doesn't require field_of_this_result. */
1906 static struct block_symbol
1907 rust_lookup_symbol (const char *name, const struct block *block,
1908 const domain_enum domain)
1910 struct block_symbol result;
1912 munge_name_and_block (&name, &block);
1914 result = lookup_symbol (name, block, domain, NULL);
1915 if (result.symbol != NULL)
1916 update_innermost_block (result);
1920 /* Look up a type, following Rust namespace conventions. */
1922 static struct type *
1923 rust_lookup_type (const char *name, const struct block *block)
1925 struct block_symbol result;
1928 munge_name_and_block (&name, &block);
1930 result = lookup_symbol (name, block, STRUCT_DOMAIN, NULL);
1931 if (result.symbol != NULL)
1933 update_innermost_block (result);
1934 return SYMBOL_TYPE (result.symbol);
1937 type = lookup_typename (parse_language (pstate), parse_gdbarch (pstate),
1942 /* Last chance, try a built-in type. */
1943 return language_lookup_primitive_type (parse_language (pstate),
1944 parse_gdbarch (pstate),
1948 static struct type *convert_ast_to_type (struct parser_state *state,
1949 const struct rust_op *operation);
1950 static const char *convert_name (struct parser_state *state,
1951 const struct rust_op *operation);
1953 /* Convert a vector of rust_ops representing types to a vector of
1956 static std::vector<struct type *>
1957 convert_params_to_types (struct parser_state *state, VEC (rust_op_ptr) *params)
1960 const struct rust_op *op;
1961 std::vector<struct type *> result;
1963 for (i = 0; VEC_iterate (rust_op_ptr, params, i, op); ++i)
1964 result.push_back (convert_ast_to_type (state, op));
1969 /* Convert a rust_op representing a type to a struct type *. */
1971 static struct type *
1972 convert_ast_to_type (struct parser_state *state,
1973 const struct rust_op *operation)
1975 struct type *type, *result = NULL;
1977 if (operation->opcode == OP_VAR_VALUE)
1979 const char *varname = convert_name (state, operation);
1981 result = rust_lookup_type (varname, expression_context_block);
1983 error (_("No typed name '%s' in current context"), varname);
1987 gdb_assert (operation->opcode == OP_TYPE);
1989 switch (operation->typecode)
1991 case TYPE_CODE_ARRAY:
1992 type = convert_ast_to_type (state, operation->left.op);
1993 if (operation->right.typed_val_int.val < 0)
1994 error (_("Negative array length"));
1995 result = lookup_array_range_type (type, 0,
1996 operation->right.typed_val_int.val - 1);
1999 case TYPE_CODE_COMPLEX:
2001 struct type *usize = rust_type ("usize");
2003 type = convert_ast_to_type (state, operation->left.op);
2004 result = rust_slice_type ("&[*gdb*]", type, usize);
2010 /* For now we treat &x and *x identically. */
2011 type = convert_ast_to_type (state, operation->left.op);
2012 result = lookup_pointer_type (type);
2015 case TYPE_CODE_FUNC:
2017 std::vector<struct type *> args
2018 (convert_params_to_types (state, *operation->right.params));
2019 struct type **argtypes = NULL;
2021 type = convert_ast_to_type (state, operation->left.op);
2023 argtypes = args.data ();
2026 = lookup_function_type_with_arguments (type, args.size (),
2028 result = lookup_pointer_type (result);
2032 case TYPE_CODE_STRUCT:
2034 std::vector<struct type *> args
2035 (convert_params_to_types (state, *operation->left.params));
2040 obstack_1grow (&work_obstack, '(');
2041 for (i = 0; i < args.size (); ++i)
2043 std::string type_name = type_to_string (args[i]);
2046 obstack_1grow (&work_obstack, ',');
2047 obstack_grow_str (&work_obstack, type_name.c_str ());
2050 obstack_grow_str0 (&work_obstack, ")");
2051 name = (const char *) obstack_finish (&work_obstack);
2053 /* We don't allow creating new tuple types (yet), but we do
2054 allow looking up existing tuple types. */
2055 result = rust_lookup_type (name, expression_context_block);
2057 error (_("could not find tuple type '%s'"), name);
2062 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_type");
2065 gdb_assert (result != NULL);
2069 /* A helper function to turn a rust_op representing a name into a full
2070 name. This applies generic arguments as needed. The returned name
2071 is allocated on the work obstack. */
2074 convert_name (struct parser_state *state, const struct rust_op *operation)
2078 gdb_assert (operation->opcode == OP_VAR_VALUE);
2080 if (operation->right.params == NULL)
2081 return operation->left.sval.ptr;
2083 std::vector<struct type *> types
2084 (convert_params_to_types (state, *operation->right.params));
2086 obstack_grow_str (&work_obstack, operation->left.sval.ptr);
2087 obstack_1grow (&work_obstack, '<');
2088 for (i = 0; i < types.size (); ++i)
2090 std::string type_name = type_to_string (types[i]);
2093 obstack_1grow (&work_obstack, ',');
2095 obstack_grow_str (&work_obstack, type_name.c_str ());
2097 obstack_grow_str0 (&work_obstack, ">");
2099 return (const char *) obstack_finish (&work_obstack);
2102 static void convert_ast_to_expression (struct parser_state *state,
2103 const struct rust_op *operation,
2104 const struct rust_op *top);
2106 /* A helper function that converts a vec of rust_ops to a gdb
2110 convert_params_to_expression (struct parser_state *state,
2111 VEC (rust_op_ptr) *params,
2112 const struct rust_op *top)
2117 for (i = 0; VEC_iterate (rust_op_ptr, params, i, elem); ++i)
2118 convert_ast_to_expression (state, elem, top);
2121 /* Lower a rust_op to a gdb expression. STATE is the parser state.
2122 OPERATION is the operation to lower. TOP is a pointer to the
2123 top-most operation; it is used to handle the special case where the
2124 top-most expression is an identifier and can be optionally lowered
2128 convert_ast_to_expression (struct parser_state *state,
2129 const struct rust_op *operation,
2130 const struct rust_op *top)
2132 switch (operation->opcode)
2135 write_exp_elt_opcode (state, OP_LONG);
2136 write_exp_elt_type (state, operation->left.typed_val_int.type);
2137 write_exp_elt_longcst (state, operation->left.typed_val_int.val);
2138 write_exp_elt_opcode (state, OP_LONG);
2142 write_exp_elt_opcode (state, OP_DOUBLE);
2143 write_exp_elt_type (state, operation->left.typed_val_float.type);
2144 write_exp_elt_dblcst (state, operation->left.typed_val_float.dval);
2145 write_exp_elt_opcode (state, OP_DOUBLE);
2148 case STRUCTOP_STRUCT:
2150 convert_ast_to_expression (state, operation->left.op, top);
2152 if (operation->completing)
2153 mark_struct_expression (state);
2154 write_exp_elt_opcode (state, STRUCTOP_STRUCT);
2155 write_exp_string (state, operation->right.sval);
2156 write_exp_elt_opcode (state, STRUCTOP_STRUCT);
2160 case STRUCTOP_ANONYMOUS:
2162 convert_ast_to_expression (state, operation->left.op, top);
2164 write_exp_elt_opcode (state, STRUCTOP_ANONYMOUS);
2165 write_exp_elt_longcst (state, operation->right.typed_val_int.val);
2166 write_exp_elt_opcode (state, STRUCTOP_ANONYMOUS);
2172 case UNOP_COMPLEMENT:
2176 convert_ast_to_expression (state, operation->left.op, top);
2177 write_exp_elt_opcode (state, operation->opcode);
2180 case BINOP_SUBSCRIPT:
2187 case BINOP_BITWISE_AND:
2188 case BINOP_BITWISE_IOR:
2189 case BINOP_BITWISE_XOR:
2192 case BINOP_LOGICAL_OR:
2193 case BINOP_LOGICAL_AND:
2195 case BINOP_NOTEQUAL:
2202 convert_ast_to_expression (state, operation->left.op, top);
2203 convert_ast_to_expression (state, operation->right.op, top);
2204 if (operation->compound_assignment)
2206 write_exp_elt_opcode (state, BINOP_ASSIGN_MODIFY);
2207 write_exp_elt_opcode (state, operation->opcode);
2208 write_exp_elt_opcode (state, BINOP_ASSIGN_MODIFY);
2211 write_exp_elt_opcode (state, operation->opcode);
2213 if (operation->compound_assignment
2214 || operation->opcode == BINOP_ASSIGN)
2218 type = language_lookup_primitive_type (parse_language (state),
2219 parse_gdbarch (state),
2222 write_exp_elt_opcode (state, OP_LONG);
2223 write_exp_elt_type (state, type);
2224 write_exp_elt_longcst (state, 0);
2225 write_exp_elt_opcode (state, OP_LONG);
2227 write_exp_elt_opcode (state, BINOP_COMMA);
2233 struct type *type = convert_ast_to_type (state, operation->right.op);
2235 convert_ast_to_expression (state, operation->left.op, top);
2236 write_exp_elt_opcode (state, UNOP_CAST);
2237 write_exp_elt_type (state, type);
2238 write_exp_elt_opcode (state, UNOP_CAST);
2244 if (operation->left.op->opcode == OP_VAR_VALUE)
2247 const char *varname = convert_name (state, operation->left.op);
2249 type = rust_lookup_type (varname, expression_context_block);
2252 /* This is actually a tuple struct expression, not a
2256 VEC (rust_op_ptr) *params = *operation->right.params;
2258 if (TYPE_CODE (type) != TYPE_CODE_NAMESPACE)
2260 if (!rust_tuple_struct_type_p (type))
2261 error (_("Type %s is not a tuple struct"), varname);
2264 VEC_iterate (rust_op_ptr, params, i, elem);
2267 char *cell = get_print_cell ();
2269 xsnprintf (cell, PRINT_CELL_SIZE, "__%d", i);
2270 write_exp_elt_opcode (state, OP_NAME);
2271 write_exp_string (state, make_stoken (cell));
2272 write_exp_elt_opcode (state, OP_NAME);
2274 convert_ast_to_expression (state, elem, top);
2277 write_exp_elt_opcode (state, OP_AGGREGATE);
2278 write_exp_elt_type (state, type);
2279 write_exp_elt_longcst (state,
2280 2 * VEC_length (rust_op_ptr,
2282 write_exp_elt_opcode (state, OP_AGGREGATE);
2287 convert_ast_to_expression (state, operation->left.op, top);
2288 convert_params_to_expression (state, *operation->right.params, top);
2289 write_exp_elt_opcode (state, OP_FUNCALL);
2290 write_exp_elt_longcst (state, VEC_length (rust_op_ptr,
2291 *operation->right.params));
2292 write_exp_elt_longcst (state, OP_FUNCALL);
2297 gdb_assert (operation->left.op == NULL);
2298 convert_params_to_expression (state, *operation->right.params, top);
2299 write_exp_elt_opcode (state, OP_ARRAY);
2300 write_exp_elt_longcst (state, 0);
2301 write_exp_elt_longcst (state, VEC_length (rust_op_ptr,
2302 *operation->right.params) - 1);
2303 write_exp_elt_longcst (state, OP_ARRAY);
2308 struct block_symbol sym;
2309 const char *varname;
2311 if (operation->left.sval.ptr[0] == '$')
2313 write_dollar_variable (state, operation->left.sval);
2317 varname = convert_name (state, operation);
2318 sym = rust_lookup_symbol (varname, expression_context_block,
2320 if (sym.symbol != NULL)
2322 write_exp_elt_opcode (state, OP_VAR_VALUE);
2323 write_exp_elt_block (state, sym.block);
2324 write_exp_elt_sym (state, sym.symbol);
2325 write_exp_elt_opcode (state, OP_VAR_VALUE);
2331 type = rust_lookup_type (varname, expression_context_block);
2333 error (_("No symbol '%s' in current context"), varname);
2335 if (TYPE_CODE (type) == TYPE_CODE_STRUCT
2336 && TYPE_NFIELDS (type) == 0)
2338 /* A unit-like struct. */
2339 write_exp_elt_opcode (state, OP_AGGREGATE);
2340 write_exp_elt_type (state, type);
2341 write_exp_elt_longcst (state, 0);
2342 write_exp_elt_opcode (state, OP_AGGREGATE);
2344 else if (operation == top)
2346 write_exp_elt_opcode (state, OP_TYPE);
2347 write_exp_elt_type (state, type);
2348 write_exp_elt_opcode (state, OP_TYPE);
2359 struct set_field *init;
2360 VEC (set_field) *fields = *operation->right.field_inits;
2365 for (i = 0; VEC_iterate (set_field, fields, i, init); ++i)
2367 if (init->name.ptr != NULL)
2369 write_exp_elt_opcode (state, OP_NAME);
2370 write_exp_string (state, init->name);
2371 write_exp_elt_opcode (state, OP_NAME);
2375 convert_ast_to_expression (state, init->init, top);
2378 if (init->name.ptr == NULL)
2380 /* This is handled differently from Ada in our
2382 write_exp_elt_opcode (state, OP_OTHERS);
2386 name = convert_name (state, operation->left.op);
2387 type = rust_lookup_type (name, expression_context_block);
2389 error (_("Could not find type '%s'"), operation->left.sval.ptr);
2391 if (TYPE_CODE (type) != TYPE_CODE_STRUCT
2392 || rust_tuple_type_p (type)
2393 || rust_tuple_struct_type_p (type))
2394 error (_("Struct expression applied to non-struct type"));
2396 write_exp_elt_opcode (state, OP_AGGREGATE);
2397 write_exp_elt_type (state, type);
2398 write_exp_elt_longcst (state, length);
2399 write_exp_elt_opcode (state, OP_AGGREGATE);
2405 write_exp_elt_opcode (state, OP_STRING);
2406 write_exp_string (state, operation->left.sval);
2407 write_exp_elt_opcode (state, OP_STRING);
2413 enum range_type kind = BOTH_BOUND_DEFAULT;
2415 if (operation->left.op != NULL)
2417 convert_ast_to_expression (state, operation->left.op, top);
2418 kind = HIGH_BOUND_DEFAULT;
2420 if (operation->right.op != NULL)
2422 convert_ast_to_expression (state, operation->right.op, top);
2423 if (kind == BOTH_BOUND_DEFAULT)
2424 kind = LOW_BOUND_DEFAULT;
2427 gdb_assert (kind == HIGH_BOUND_DEFAULT);
2428 kind = NONE_BOUND_DEFAULT;
2431 write_exp_elt_opcode (state, OP_RANGE);
2432 write_exp_elt_longcst (state, kind);
2433 write_exp_elt_opcode (state, OP_RANGE);
2438 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_expression");
2444 /* The parser as exposed to gdb. */
2447 rust_parse (struct parser_state *state)
2450 struct cleanup *cleanup;
2452 obstack_init (&work_obstack);
2453 cleanup = make_cleanup_obstack_free (&work_obstack);
2457 result = rustyyparse ();
2459 if (!result || (parse_completion && rust_ast != NULL))
2461 const struct rust_op *ast = rust_ast;
2464 gdb_assert (ast != NULL);
2465 convert_ast_to_expression (state, ast, ast);
2468 do_cleanups (cleanup);
2472 /* The parser error handler. */
2475 rustyyerror (char *msg)
2477 const char *where = prev_lexptr ? prev_lexptr : lexptr;
2478 error (_("%s in expression, near `%s'."), (msg ? msg : "Error"), where);
2485 /* Initialize the lexer for testing. */
2488 rust_lex_test_init (const char *input)
2495 /* A test helper that lexes a string, expecting a single token. It
2496 returns the lexer data for this token. */
2499 rust_lex_test_one (const char *input, int expected)
2504 rust_lex_test_init (input);
2506 token = rustyylex ();
2507 SELF_CHECK (token == expected);
2508 result = rustyylval;
2512 token = rustyylex ();
2513 SELF_CHECK (token == 0);
2519 /* Test that INPUT lexes as the integer VALUE. */
2522 rust_lex_int_test (const char *input, int value, int kind)
2524 RUSTSTYPE result = rust_lex_test_one (input, kind);
2525 SELF_CHECK (result.typed_val_int.val == value);
2528 /* Test that INPUT throws an exception with text ERR. */
2531 rust_lex_exception_test (const char *input, const char *err)
2535 /* The "kind" doesn't matter. */
2536 rust_lex_test_one (input, DECIMAL_INTEGER);
2539 CATCH (except, RETURN_MASK_ERROR)
2541 SELF_CHECK (strcmp (except.message, err) == 0);
2546 /* Test that INPUT lexes as the identifier, string, or byte-string
2547 VALUE. KIND holds the expected token kind. */
2550 rust_lex_stringish_test (const char *input, const char *value, int kind)
2552 RUSTSTYPE result = rust_lex_test_one (input, kind);
2553 SELF_CHECK (result.sval.length == strlen (value));
2554 SELF_CHECK (strncmp (result.sval.ptr, value, result.sval.length) == 0);
2557 /* Helper to test that a string parses as a given token sequence. */
2560 rust_lex_test_sequence (const char *input, int len, const int expected[])
2567 for (i = 0; i < len; ++i)
2569 int token = rustyylex ();
2571 SELF_CHECK (token == expected[i]);
2575 /* Tests for an integer-parsing corner case. */
2578 rust_lex_test_trailing_dot (void)
2580 const int expected1[] = { DECIMAL_INTEGER, '.', IDENT, '(', ')', 0 };
2581 const int expected2[] = { INTEGER, '.', IDENT, '(', ')', 0 };
2582 const int expected3[] = { FLOAT, EQEQ, '(', ')', 0 };
2583 const int expected4[] = { DECIMAL_INTEGER, DOTDOT, DECIMAL_INTEGER, 0 };
2585 rust_lex_test_sequence ("23.g()", ARRAY_SIZE (expected1), expected1);
2586 rust_lex_test_sequence ("23_0.g()", ARRAY_SIZE (expected2), expected2);
2587 rust_lex_test_sequence ("23.==()", ARRAY_SIZE (expected3), expected3);
2588 rust_lex_test_sequence ("23..25", ARRAY_SIZE (expected4), expected4);
2591 /* Tests of completion. */
2594 rust_lex_test_completion (void)
2596 const int expected[] = { IDENT, '.', COMPLETE, 0 };
2598 parse_completion = 1;
2600 rust_lex_test_sequence ("something.wha", ARRAY_SIZE (expected), expected);
2601 rust_lex_test_sequence ("something.", ARRAY_SIZE (expected), expected);
2603 parse_completion = 0;
2606 /* Test pushback. */
2609 rust_lex_test_push_back (void)
2613 rust_lex_test_init (">>=");
2615 token = rustyylex ();
2616 SELF_CHECK (token == COMPOUND_ASSIGN);
2617 SELF_CHECK (rustyylval.opcode == BINOP_RSH);
2619 rust_push_back ('=');
2621 token = rustyylex ();
2622 SELF_CHECK (token == '=');
2624 token = rustyylex ();
2625 SELF_CHECK (token == 0);
2628 /* Unit test the lexer. */
2631 rust_lex_tests (void)
2635 obstack_init (&work_obstack);
2638 rust_lex_test_one ("", 0);
2639 rust_lex_test_one (" \t \n \r ", 0);
2640 rust_lex_test_one ("thread 23", 0);
2641 rust_lex_test_one ("task 23", 0);
2642 rust_lex_test_one ("th 104", 0);
2643 rust_lex_test_one ("ta 97", 0);
2645 rust_lex_int_test ("'z'", 'z', INTEGER);
2646 rust_lex_int_test ("'\\xff'", 0xff, INTEGER);
2647 rust_lex_int_test ("'\\u{1016f}'", 0x1016f, INTEGER);
2648 rust_lex_int_test ("b'z'", 'z', INTEGER);
2649 rust_lex_int_test ("b'\\xfe'", 0xfe, INTEGER);
2650 rust_lex_int_test ("b'\\xFE'", 0xfe, INTEGER);
2651 rust_lex_int_test ("b'\\xfE'", 0xfe, INTEGER);
2653 /* Test all escapes in both modes. */
2654 rust_lex_int_test ("'\\n'", '\n', INTEGER);
2655 rust_lex_int_test ("'\\r'", '\r', INTEGER);
2656 rust_lex_int_test ("'\\t'", '\t', INTEGER);
2657 rust_lex_int_test ("'\\\\'", '\\', INTEGER);
2658 rust_lex_int_test ("'\\0'", '\0', INTEGER);
2659 rust_lex_int_test ("'\\''", '\'', INTEGER);
2660 rust_lex_int_test ("'\\\"'", '"', INTEGER);
2662 rust_lex_int_test ("b'\\n'", '\n', INTEGER);
2663 rust_lex_int_test ("b'\\r'", '\r', INTEGER);
2664 rust_lex_int_test ("b'\\t'", '\t', INTEGER);
2665 rust_lex_int_test ("b'\\\\'", '\\', INTEGER);
2666 rust_lex_int_test ("b'\\0'", '\0', INTEGER);
2667 rust_lex_int_test ("b'\\''", '\'', INTEGER);
2668 rust_lex_int_test ("b'\\\"'", '"', INTEGER);
2670 rust_lex_exception_test ("'z", "Unterminated character literal");
2671 rust_lex_exception_test ("b'\\x0'", "Not enough hex digits seen");
2672 rust_lex_exception_test ("b'\\u{0}'", "Unicode escape in byte literal");
2673 rust_lex_exception_test ("'\\x0'", "Not enough hex digits seen");
2674 rust_lex_exception_test ("'\\u0'", "Missing '{' in Unicode escape");
2675 rust_lex_exception_test ("'\\u{0", "Missing '}' in Unicode escape");
2676 rust_lex_exception_test ("'\\u{0000007}", "Overlong hex escape");
2677 rust_lex_exception_test ("'\\u{}", "Not enough hex digits seen");
2678 rust_lex_exception_test ("'\\Q'", "Invalid escape \\Q in literal");
2679 rust_lex_exception_test ("b'\\Q'", "Invalid escape \\Q in literal");
2681 rust_lex_int_test ("23", 23, DECIMAL_INTEGER);
2682 rust_lex_int_test ("2_344__29", 234429, INTEGER);
2683 rust_lex_int_test ("0x1f", 0x1f, INTEGER);
2684 rust_lex_int_test ("23usize", 23, INTEGER);
2685 rust_lex_int_test ("23i32", 23, INTEGER);
2686 rust_lex_int_test ("0x1_f", 0x1f, INTEGER);
2687 rust_lex_int_test ("0b1_101011__", 0x6b, INTEGER);
2688 rust_lex_int_test ("0o001177i64", 639, INTEGER);
2690 rust_lex_test_trailing_dot ();
2692 rust_lex_test_one ("23.", FLOAT);
2693 rust_lex_test_one ("23.99f32", FLOAT);
2694 rust_lex_test_one ("23e7", FLOAT);
2695 rust_lex_test_one ("23E-7", FLOAT);
2696 rust_lex_test_one ("23e+7", FLOAT);
2697 rust_lex_test_one ("23.99e+7f64", FLOAT);
2698 rust_lex_test_one ("23.82f32", FLOAT);
2700 rust_lex_stringish_test ("hibob", "hibob", IDENT);
2701 rust_lex_stringish_test ("hibob__93", "hibob__93", IDENT);
2702 rust_lex_stringish_test ("thread", "thread", IDENT);
2704 rust_lex_stringish_test ("\"string\"", "string", STRING);
2705 rust_lex_stringish_test ("\"str\\ting\"", "str\ting", STRING);
2706 rust_lex_stringish_test ("\"str\\\"ing\"", "str\"ing", STRING);
2707 rust_lex_stringish_test ("r\"str\\ing\"", "str\\ing", STRING);
2708 rust_lex_stringish_test ("r#\"str\\ting\"#", "str\\ting", STRING);
2709 rust_lex_stringish_test ("r###\"str\\\"ing\"###", "str\\\"ing", STRING);
2711 rust_lex_stringish_test ("b\"string\"", "string", BYTESTRING);
2712 rust_lex_stringish_test ("b\"\x73tring\"", "string", BYTESTRING);
2713 rust_lex_stringish_test ("b\"str\\\"ing\"", "str\"ing", BYTESTRING);
2714 rust_lex_stringish_test ("br####\"\\x73tring\"####", "\\x73tring",
2717 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
2718 rust_lex_test_one (identifier_tokens[i].name, identifier_tokens[i].value);
2720 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
2721 rust_lex_test_one (operator_tokens[i].name, operator_tokens[i].value);
2723 rust_lex_test_completion ();
2724 rust_lex_test_push_back ();
2726 obstack_free (&work_obstack, NULL);
2730 #endif /* GDB_SELF_TEST */
2733 _initialize_rust_exp (void)
2735 int code = regcomp (&number_regex, number_regex_text, REG_EXTENDED);
2736 /* If the regular expression was incorrect, it was a programming
2738 gdb_assert (code == 0);
2741 register_self_test (rust_lex_tests);