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"
30 #include "gdb_obstack.h"
31 #include "gdb_regex.h"
32 #include "rust-lang.h"
33 #include "parser-defs.h"
38 #define GDB_YY_REMAP_PREFIX rust
41 #define RUSTSTYPE YYSTYPE
43 extern initialize_file_ftype _initialize_rust_exp;
46 typedef const struct rust_op *rust_op_ptr;
47 DEF_VEC_P (rust_op_ptr);
49 /* A typed integer constant. */
57 /* A typed floating point constant. */
59 struct typed_val_float
65 /* An identifier and an expression. This is used to represent one
66 element of a struct initializer. */
71 const struct rust_op *init;
74 typedef struct set_field set_field;
76 DEF_VEC_O (set_field);
79 static int rustyylex (void);
80 static void rust_push_back (char c);
81 static const char *rust_copy_name (const char *, int);
82 static struct stoken rust_concat3 (const char *, const char *, const char *);
83 static struct stoken make_stoken (const char *);
84 static struct block_symbol rust_lookup_symbol (const char *name,
85 const struct block *block,
86 const domain_enum domain);
87 static struct type *rust_lookup_type (const char *name,
88 const struct block *block);
89 static struct type *rust_type (const char *name);
91 static const struct rust_op *crate_name (const struct rust_op *name);
92 static const struct rust_op *super_name (const struct rust_op *name,
93 unsigned int n_supers);
95 static const struct rust_op *ast_operation (enum exp_opcode opcode,
96 const struct rust_op *left,
97 const struct rust_op *right);
98 static const struct rust_op *ast_compound_assignment
99 (enum exp_opcode opcode, const struct rust_op *left,
100 const struct rust_op *rust_op);
101 static const struct rust_op *ast_literal (struct typed_val_int val);
102 static const struct rust_op *ast_dliteral (struct typed_val_float val);
103 static const struct rust_op *ast_structop (const struct rust_op *left,
106 static const struct rust_op *ast_structop_anonymous
107 (const struct rust_op *left, struct typed_val_int number);
108 static const struct rust_op *ast_unary (enum exp_opcode opcode,
109 const struct rust_op *expr);
110 static const struct rust_op *ast_cast (const struct rust_op *expr,
111 const struct rust_op *type);
112 static const struct rust_op *ast_call_ish (enum exp_opcode opcode,
113 const struct rust_op *expr,
114 VEC (rust_op_ptr) **params);
115 static const struct rust_op *ast_path (struct stoken name,
116 VEC (rust_op_ptr) **params);
117 static const struct rust_op *ast_string (struct stoken str);
118 static const struct rust_op *ast_struct (const struct rust_op *name,
119 VEC (set_field) **fields);
120 static const struct rust_op *ast_range (const struct rust_op *lhs,
121 const struct rust_op *rhs);
122 static const struct rust_op *ast_array_type (const struct rust_op *lhs,
123 struct typed_val_int val);
124 static const struct rust_op *ast_slice_type (const struct rust_op *type);
125 static const struct rust_op *ast_reference_type (const struct rust_op *type);
126 static const struct rust_op *ast_pointer_type (const struct rust_op *type,
128 static const struct rust_op *ast_function_type (const struct rust_op *result,
129 VEC (rust_op_ptr) **params);
130 static const struct rust_op *ast_tuple_type (VEC (rust_op_ptr) **params);
132 /* The state of the parser, used internally when we are parsing the
135 static struct parser_state *pstate = NULL;
137 /* A regular expression for matching Rust numbers. This is split up
138 since it is very long and this gives us a way to comment the
141 static const char *number_regex_text =
142 /* subexpression 1: allows use of alternation, otherwise uninteresting */
144 /* First comes floating point. */
145 /* Recognize number after the decimal point, with optional
146 exponent and optional type suffix.
147 subexpression 2: allows "?", otherwise uninteresting
148 subexpression 3: if present, type suffix
150 "[0-9][0-9_]*\\.[0-9][0-9_]*([eE][-+]?[0-9][0-9_]*)?(f32|f64)?"
151 #define FLOAT_TYPE1 3
153 /* Recognize exponent without decimal point, with optional type
155 subexpression 4: if present, type suffix
157 #define FLOAT_TYPE2 4
158 "[0-9][0-9_]*[eE][-+]?[0-9][0-9_]*(f32|f64)?"
160 /* "23." is a valid floating point number, but "23.e5" and
161 "23.f32" are not. So, handle the trailing-. case
165 /* Finally come integers.
166 subexpression 5: text of integer
167 subexpression 6: if present, type suffix
168 subexpression 7: allows use of alternation, otherwise uninteresting
172 "(0x[a-fA-F0-9_]+|0o[0-7_]+|0b[01_]+|[0-9][0-9_]*)"
173 "([iu](size|8|16|32|64))?"
175 /* The number of subexpressions to allocate space for, including the
176 "0th" whole match subexpression. */
177 #define NUM_SUBEXPRESSIONS 8
179 /* The compiled number-matching regex. */
181 static regex_t number_regex;
183 /* True if we're running unit tests. */
185 static int unit_testing;
187 /* Obstack for data temporarily allocated during parsing. */
189 static struct obstack work_obstack;
191 /* Result of parsing. Points into work_obstack. */
193 static const struct rust_op *rust_ast;
199 /* A typed integer constant. */
200 struct typed_val_int typed_val_int;
202 /* A typed floating point constant. */
203 struct typed_val_float typed_val_float;
205 /* An identifier or string. */
208 /* A token representing an opcode, like "==". */
209 enum exp_opcode opcode;
211 /* A list of expressions; for example, the arguments to a function
213 VEC (rust_op_ptr) **params;
215 /* A list of field initializers. */
216 VEC (set_field) **field_inits;
218 /* A single field initializer. */
219 struct set_field one_field_init;
222 const struct rust_op *op;
224 /* A plain integer, for example used to count the number of
225 "super::" prefixes on a path. */
231 /* Rust AST operations. We build a tree of these; then lower them
232 to gdb expressions when parsing has completed. */
237 enum exp_opcode opcode;
238 /* If OPCODE is OP_TYPE, then this holds information about what type
239 is described by this node. */
240 enum type_code typecode;
241 /* Indicates whether OPCODE actually represents a compound
242 assignment. For example, if OPCODE is GTGT and this is false,
243 then this rust_op represents an ordinary ">>"; but if this is
244 true, then this rust_op represents ">>=". Unused in other
246 unsigned int compound_assignment : 1;
247 /* Only used by a field expression; if set, indicates that the field
248 name occurred at the end of the expression and is eligible for
250 unsigned int completing : 1;
251 /* Operands of expression. Which one is used and how depends on the
252 particular opcode. */
261 %token <sval> COMPLETE
262 %token <typed_val_int> INTEGER
263 %token <typed_val_int> DECIMAL_INTEGER
265 %token <sval> BYTESTRING
266 %token <typed_val_float> FLOAT
267 %token <opcode> COMPOUND_ASSIGN
269 /* Keyword tokens. */
270 %token <voidval> KW_AS
271 %token <voidval> KW_IF
272 %token <voidval> KW_TRUE
273 %token <voidval> KW_FALSE
274 %token <voidval> KW_SUPER
275 %token <voidval> KW_SELF
276 %token <voidval> KW_MUT
277 %token <voidval> KW_EXTERN
278 %token <voidval> KW_CONST
279 %token <voidval> KW_FN
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
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); }
432 /* S{} is documented as valid but seems to be an unstable feature, so
433 it is left out here. */
437 VEC (set_field) **result
438 = OBSTACK_ZALLOC (&work_obstack, VEC (set_field) *);
440 make_cleanup (VEC_cleanup (set_field), result);
441 VEC_safe_push (set_field, *result, &$1);
445 | IDENT ':' expr ',' struct_expr_list
451 VEC_safe_push (set_field, *$5, &sf);
457 '[' KW_MUT expr_list ']'
458 { $$ = ast_call_ish (OP_ARRAY, NULL, $3); }
460 { $$ = ast_call_ish (OP_ARRAY, NULL, $2); }
461 | '[' KW_MUT expr ';' expr ']'
462 { $$ = ast_operation (OP_RUST_ARRAY, $3, $5); }
463 | '[' expr ';' expr ']'
464 { $$ = ast_operation (OP_RUST_ARRAY, $2, $4); }
469 { $$ = ast_range ($1, NULL); }
471 { $$ = ast_range ($1, $3); }
473 { $$ = ast_range (NULL, $2); }
475 { $$ = ast_range (NULL, NULL); }
480 { $$ = ast_literal ($1); }
482 { $$ = ast_literal ($1); }
484 { $$ = ast_dliteral ($1); }
487 const struct rust_op *str = ast_string ($1);
488 VEC (set_field) **fields;
489 struct set_field field;
490 struct typed_val_int val;
493 fields = OBSTACK_ZALLOC (&work_obstack, VEC (set_field) *);
494 make_cleanup (VEC_cleanup (set_field), fields);
496 /* Wrap the raw string in the &str struct. */
497 field.name.ptr = "data_ptr";
498 field.name.length = strlen (field.name.ptr);
499 field.init = ast_unary (UNOP_ADDR, ast_string ($1));
500 VEC_safe_push (set_field, *fields, &field);
502 val.type = rust_type ("usize");
505 field.name.ptr = "length";
506 field.name.length = strlen (field.name.ptr);
507 field.init = ast_literal (val);
508 VEC_safe_push (set_field, *fields, &field);
511 token.length = strlen (token.ptr);
512 $$ = ast_struct (ast_path (token, NULL), fields);
515 { $$ = ast_string ($1); }
518 struct typed_val_int val;
520 val.type = language_bool_type (parse_language (pstate),
521 parse_gdbarch (pstate));
523 $$ = ast_literal (val);
527 struct typed_val_int val;
529 val.type = language_bool_type (parse_language (pstate),
530 parse_gdbarch (pstate));
532 $$ = ast_literal (val);
538 { $$ = ast_structop ($1, $3.ptr, 0); }
541 $$ = ast_structop ($1, $3.ptr, 1);
544 | expr '.' DECIMAL_INTEGER
545 { $$ = ast_structop_anonymous ($1, $3); }
550 { $$ = ast_operation (BINOP_SUBSCRIPT, $1, $3); }
555 { $$ = ast_unary (UNOP_PLUS, $2); }
557 | '-' expr %prec UNARY
558 { $$ = ast_unary (UNOP_NEG, $2); }
560 | '!' expr %prec UNARY
562 /* Note that we provide a Rust-specific evaluator
563 override for UNOP_COMPLEMENT, so it can do the
564 right thing for both bool and integral
566 $$ = ast_unary (UNOP_COMPLEMENT, $2);
569 | '*' expr %prec UNARY
570 { $$ = ast_unary (UNOP_IND, $2); }
572 | '&' expr %prec UNARY
573 { $$ = ast_unary (UNOP_ADDR, $2); }
575 | '&' KW_MUT expr %prec UNARY
576 { $$ = ast_unary (UNOP_ADDR, $3); }
584 | compound_assignment_expr
589 { $$ = ast_operation (BINOP_MUL, $1, $3); }
592 { $$ = ast_operation (BINOP_REPEAT, $1, $3); }
595 { $$ = ast_operation (BINOP_DIV, $1, $3); }
598 { $$ = ast_operation (BINOP_REM, $1, $3); }
601 { $$ = ast_operation (BINOP_LESS, $1, $3); }
604 { $$ = ast_operation (BINOP_GTR, $1, $3); }
607 { $$ = ast_operation (BINOP_BITWISE_AND, $1, $3); }
610 { $$ = ast_operation (BINOP_BITWISE_IOR, $1, $3); }
613 { $$ = ast_operation (BINOP_BITWISE_XOR, $1, $3); }
616 { $$ = ast_operation (BINOP_ADD, $1, $3); }
619 { $$ = ast_operation (BINOP_SUB, $1, $3); }
622 { $$ = ast_operation (BINOP_LOGICAL_OR, $1, $3); }
625 { $$ = ast_operation (BINOP_LOGICAL_AND, $1, $3); }
628 { $$ = ast_operation (BINOP_EQUAL, $1, $3); }
631 { $$ = ast_operation (BINOP_NOTEQUAL, $1, $3); }
634 { $$ = ast_operation (BINOP_LEQ, $1, $3); }
637 { $$ = ast_operation (BINOP_GEQ, $1, $3); }
640 { $$ = ast_operation (BINOP_LSH, $1, $3); }
643 { $$ = ast_operation (BINOP_RSH, $1, $3); }
648 { $$ = ast_cast ($1, $3); }
653 { $$ = ast_operation (BINOP_ASSIGN, $1, $3); }
656 compound_assignment_expr:
657 expr COMPOUND_ASSIGN expr
658 { $$ = ast_compound_assignment ($2, $1, $3); }
670 $$ = OBSTACK_ZALLOC (&work_obstack, VEC (rust_op_ptr) *);
671 make_cleanup (VEC_cleanup (rust_op_ptr), $$);
672 VEC_safe_push (rust_op_ptr, *$$, $1);
676 VEC_safe_push (rust_op_ptr, *$1, $3);
684 /* The result can't be NULL. */
685 $$ = OBSTACK_ZALLOC (&work_obstack, VEC (rust_op_ptr) *);
686 make_cleanup (VEC_cleanup (rust_op_ptr), $$);
701 { $$ = ast_call_ish (OP_FUNCALL, $1, $2); }
712 | super_path KW_SUPER COLONCOLON
720 { $$ = ast_path ($1, NULL); }
722 { $$ = ast_path (make_stoken ("self"), NULL); }
726 identifier_path_for_expr
727 | KW_SELF COLONCOLON identifier_path_for_expr
728 { $$ = super_name ($3, 0); }
729 | maybe_self_path super_path identifier_path_for_expr
730 { $$ = super_name ($3, $2); }
731 | COLONCOLON identifier_path_for_expr
732 { $$ = crate_name ($2); }
733 | KW_EXTERN identifier_path_for_expr
735 /* This is a gdb extension to make it possible to
736 refer to items in other crates. It just bypasses
737 adding the current crate to the front of the
739 $$ = ast_path (rust_concat3 ("::", $2->left.sval.ptr, NULL),
744 identifier_path_for_expr:
746 { $$ = ast_path ($1, NULL); }
747 | identifier_path_for_expr COLONCOLON IDENT
749 $$ = ast_path (rust_concat3 ($1->left.sval.ptr, "::",
753 | identifier_path_for_expr COLONCOLON '<' type_list '>'
754 { $$ = ast_path ($1->left.sval, $4); }
755 | identifier_path_for_expr COLONCOLON '<' type_list RSH
757 $$ = ast_path ($1->left.sval, $4);
758 rust_push_back ('>');
763 identifier_path_for_type
764 | KW_SELF COLONCOLON identifier_path_for_type
765 { $$ = super_name ($3, 0); }
766 | maybe_self_path super_path identifier_path_for_type
767 { $$ = super_name ($3, $2); }
768 | COLONCOLON identifier_path_for_type
769 { $$ = crate_name ($2); }
770 | KW_EXTERN identifier_path_for_type
772 /* This is a gdb extension to make it possible to
773 refer to items in other crates. It just bypasses
774 adding the current crate to the front of the
776 $$ = ast_path (rust_concat3 ("::", $2->left.sval.ptr, NULL),
781 just_identifiers_for_type:
783 { $$ = ast_path ($1, NULL); }
784 | just_identifiers_for_type COLONCOLON IDENT
786 $$ = ast_path (rust_concat3 ($1->left.sval.ptr, "::",
792 identifier_path_for_type:
793 just_identifiers_for_type
794 | just_identifiers_for_type '<' type_list '>'
795 { $$ = ast_path ($1->left.sval, $3); }
796 | just_identifiers_for_type '<' type_list RSH
798 $$ = ast_path ($1->left.sval, $3);
799 rust_push_back ('>');
805 | '[' type ';' INTEGER ']'
806 { $$ = ast_array_type ($2, $4); }
807 | '[' type ';' DECIMAL_INTEGER ']'
808 { $$ = ast_array_type ($2, $4); }
810 { $$ = ast_slice_type ($3); }
812 { $$ = ast_reference_type ($2); }
814 { $$ = ast_pointer_type ($3, 1); }
816 { $$ = ast_pointer_type ($3, 0); }
817 | KW_FN '(' maybe_type_list ')' ARROW type
818 { $$ = ast_function_type ($6, $3); }
819 | '(' maybe_type_list ')'
820 { $$ = ast_tuple_type ($2); }
833 VEC (rust_op_ptr) **result
834 = OBSTACK_ZALLOC (&work_obstack, VEC (rust_op_ptr) *);
836 make_cleanup (VEC_cleanup (rust_op_ptr), result);
837 VEC_safe_push (rust_op_ptr, *result, $1);
842 VEC_safe_push (rust_op_ptr, *$1, $3);
849 /* A struct of this type is used to describe a token. */
855 enum exp_opcode opcode;
858 /* Identifier tokens. */
860 static const struct token_info identifier_tokens[] =
862 { "as", KW_AS, OP_NULL },
863 { "false", KW_FALSE, OP_NULL },
864 { "if", 0, OP_NULL },
865 { "mut", KW_MUT, OP_NULL },
866 { "const", KW_CONST, OP_NULL },
867 { "self", KW_SELF, OP_NULL },
868 { "super", KW_SUPER, OP_NULL },
869 { "true", KW_TRUE, OP_NULL },
870 { "extern", KW_EXTERN, OP_NULL },
871 { "fn", KW_FN, OP_NULL },
874 /* Operator tokens, sorted longest first. */
876 static const struct token_info operator_tokens[] =
878 { ">>=", COMPOUND_ASSIGN, BINOP_RSH },
879 { "<<=", COMPOUND_ASSIGN, BINOP_LSH },
881 { "<<", LSH, OP_NULL },
882 { ">>", RSH, OP_NULL },
883 { "&&", ANDAND, OP_NULL },
884 { "||", OROR, OP_NULL },
885 { "==", EQEQ, OP_NULL },
886 { "!=", NOTEQ, OP_NULL },
887 { "<=", LTEQ, OP_NULL },
888 { ">=", GTEQ, OP_NULL },
889 { "+=", COMPOUND_ASSIGN, BINOP_ADD },
890 { "-=", COMPOUND_ASSIGN, BINOP_SUB },
891 { "*=", COMPOUND_ASSIGN, BINOP_MUL },
892 { "/=", COMPOUND_ASSIGN, BINOP_DIV },
893 { "%=", COMPOUND_ASSIGN, BINOP_REM },
894 { "&=", COMPOUND_ASSIGN, BINOP_BITWISE_AND },
895 { "|=", COMPOUND_ASSIGN, BINOP_BITWISE_IOR },
896 { "^=", COMPOUND_ASSIGN, BINOP_BITWISE_XOR },
898 { "::", COLONCOLON, OP_NULL },
899 { "..", DOTDOT, OP_NULL },
900 { "->", ARROW, OP_NULL }
903 /* Helper function to copy to the name obstack. */
906 rust_copy_name (const char *name, int len)
908 return (const char *) obstack_copy0 (&work_obstack, name, len);
911 /* Helper function to make an stoken from a C string. */
914 make_stoken (const char *p)
916 struct stoken result;
919 result.length = strlen (result.ptr);
923 /* Helper function to concatenate three strings on the name
927 rust_concat3 (const char *s1, const char *s2, const char *s3)
929 return make_stoken (obconcat (&work_obstack, s1, s2, s3, (char *) NULL));
932 /* Return an AST node referring to NAME, but relative to the crate's
935 static const struct rust_op *
936 crate_name (const struct rust_op *name)
938 char *crate = rust_crate_for_block (expression_context_block);
939 struct stoken result;
941 gdb_assert (name->opcode == OP_VAR_VALUE);
944 error (_("Could not find crate for current location"));
945 result = make_stoken (obconcat (&work_obstack, "::", crate, "::",
946 name->left.sval.ptr, (char *) NULL));
949 return ast_path (result, name->right.params);
952 /* Create an AST node referring to a "super::" qualified name. IDENT
953 is the base name and N_SUPERS is how many "super::"s were
954 provided. N_SUPERS can be zero. */
956 static const struct rust_op *
957 super_name (const struct rust_op *ident, unsigned int n_supers)
959 const char *scope = block_scope (expression_context_block);
962 gdb_assert (ident->opcode == OP_VAR_VALUE);
964 if (scope[0] == '\0')
965 error (_("Couldn't find namespace scope for self::"));
971 VEC (int) *offsets = NULL;
972 unsigned int current_len, previous_len;
973 struct cleanup *cleanup;
975 cleanup = make_cleanup (VEC_cleanup (int), &offsets);
976 current_len = cp_find_first_component (scope);
978 while (scope[current_len] != '\0')
980 VEC_safe_push (int, offsets, current_len);
981 gdb_assert (scope[current_len] == ':');
982 previous_len = current_len;
985 current_len += cp_find_first_component (scope
989 len = VEC_length (int, offsets);
991 error (_("Too many super:: uses from '%s'"), scope);
993 offset = VEC_index (int, offsets, len - n_supers);
995 do_cleanups (cleanup);
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 char *type_name = NULL;
1425 int type_index = -1;
1428 struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
1430 match = regexec (&number_regex, lexptr, ARRAY_SIZE (subexps), subexps, 0);
1431 /* Failure means the regexp is broken. */
1432 gdb_assert (match == 0);
1434 if (subexps[INT_TEXT].rm_so != -1)
1436 /* Integer part matched. */
1438 end_index = subexps[INT_TEXT].rm_eo;
1439 if (subexps[INT_TYPE].rm_so == -1)
1443 type_index = INT_TYPE;
1444 could_be_decimal = 0;
1447 else if (subexps[FLOAT_TYPE1].rm_so != -1)
1449 /* Found floating point type suffix. */
1450 end_index = subexps[FLOAT_TYPE1].rm_so;
1451 type_index = FLOAT_TYPE1;
1453 else if (subexps[FLOAT_TYPE2].rm_so != -1)
1455 /* Found floating point type suffix. */
1456 end_index = subexps[FLOAT_TYPE2].rm_so;
1457 type_index = FLOAT_TYPE2;
1461 /* Any other floating point match. */
1462 end_index = subexps[0].rm_eo;
1466 /* We need a special case if the final character is ".". In this
1467 case we might need to parse an integer. For example, "23.f()" is
1468 a request for a trait method call, not a syntax error involving
1469 the floating point number "23.". */
1470 gdb_assert (subexps[0].rm_eo > 0);
1471 if (lexptr[subexps[0].rm_eo - 1] == '.')
1473 const char *next = skip_spaces_const (&lexptr[subexps[0].rm_eo]);
1475 if (rust_identifier_start_p (*next) || *next == '.')
1479 end_index = subexps[0].rm_eo;
1481 could_be_decimal = 1;
1485 /* Compute the type name if we haven't already. */
1486 if (type_name == NULL)
1488 gdb_assert (type_index != -1);
1489 type_name = xstrndup (lexptr + subexps[type_index].rm_so,
1490 (subexps[type_index].rm_eo
1491 - subexps[type_index].rm_so));
1492 make_cleanup (xfree, type_name);
1495 /* Look up the type. */
1496 type = rust_type (type_name);
1498 /* Copy the text of the number and remove the "_"s. */
1499 number = xstrndup (lexptr, end_index);
1500 make_cleanup (xfree, number);
1501 for (i = out = 0; number[i]; ++i)
1503 if (number[i] == '_')
1504 could_be_decimal = 0;
1506 number[out++] = number[i];
1510 /* Advance past the match. */
1511 lexptr += subexps[0].rm_eo;
1513 /* Parse the number. */
1517 if (number[0] == '0')
1519 if (number[1] == 'x')
1521 else if (number[1] == 'o')
1523 else if (number[1] == 'b')
1528 could_be_decimal = 0;
1531 rustyylval.typed_val_int.val = strtoul (number, NULL, radix);
1532 rustyylval.typed_val_int.type = type;
1536 rustyylval.typed_val_float.dval = strtod (number, NULL);
1537 rustyylval.typed_val_float.type = type;
1540 do_cleanups (cleanup);
1541 return is_integer ? (could_be_decimal ? DECIMAL_INTEGER : INTEGER) : FLOAT;
1549 /* Skip all leading whitespace. */
1550 while (lexptr[0] == ' ' || lexptr[0] == '\t' || lexptr[0] == '\r'
1551 || lexptr[0] == '\n')
1554 /* If we hit EOF and we're completing, then return COMPLETE -- maybe
1555 we're completing an empty string at the end of a field_expr.
1556 But, we don't want to return two COMPLETE tokens in a row. */
1557 if (lexptr[0] == '\0' && lexptr == prev_lexptr)
1559 prev_lexptr = lexptr;
1560 if (lexptr[0] == '\0')
1562 if (parse_completion)
1564 rustyylval.sval = make_stoken ("");
1570 if (lexptr[0] >= '0' && lexptr[0] <= '9')
1571 return lex_number ();
1572 else if (lexptr[0] == 'b' && lexptr[1] == '\'')
1573 return lex_character ();
1574 else if (lexptr[0] == 'b' && lexptr[1] == '"')
1575 return lex_string ();
1576 else if (lexptr[0] == 'b' && starts_raw_string (lexptr + 1))
1577 return lex_string ();
1578 else if (starts_raw_string (lexptr))
1579 return lex_string ();
1580 else if (rust_identifier_start_p (lexptr[0]))
1581 return lex_identifier ();
1582 else if (lexptr[0] == '"')
1583 return lex_string ();
1584 else if (lexptr[0] == '\'')
1585 return lex_character ();
1586 else if (lexptr[0] == '}' || lexptr[0] == ']')
1588 /* Falls through to lex_operator. */
1591 else if (lexptr[0] == '(' || lexptr[0] == '{')
1593 /* Falls through to lex_operator. */
1596 else if (lexptr[0] == ',' && comma_terminates && paren_depth == 0)
1599 return lex_operator ();
1602 /* Push back a single character to be re-lexed. */
1605 rust_push_back (char c)
1607 /* Can't be called before any lexing. */
1608 gdb_assert (prev_lexptr != NULL);
1611 gdb_assert (*lexptr == c);
1616 /* Make an arbitrary operation and fill in the fields. */
1618 static const struct rust_op *
1619 ast_operation (enum exp_opcode opcode, const struct rust_op *left,
1620 const struct rust_op *right)
1622 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1624 result->opcode = opcode;
1625 result->left.op = left;
1626 result->right.op = right;
1631 /* Make a compound assignment operation. */
1633 static const struct rust_op *
1634 ast_compound_assignment (enum exp_opcode opcode, const struct rust_op *left,
1635 const struct rust_op *right)
1637 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1639 result->opcode = opcode;
1640 result->compound_assignment = 1;
1641 result->left.op = left;
1642 result->right.op = right;
1647 /* Make a typed integer literal operation. */
1649 static const struct rust_op *
1650 ast_literal (struct typed_val_int val)
1652 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1654 result->opcode = OP_LONG;
1655 result->left.typed_val_int = val;
1660 /* Make a typed floating point literal operation. */
1662 static const struct rust_op *
1663 ast_dliteral (struct typed_val_float val)
1665 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1667 result->opcode = OP_DOUBLE;
1668 result->left.typed_val_float = val;
1673 /* Make a unary operation. */
1675 static const struct rust_op *
1676 ast_unary (enum exp_opcode opcode, const struct rust_op *expr)
1678 return ast_operation (opcode, expr, NULL);
1681 /* Make a cast operation. */
1683 static const struct rust_op *
1684 ast_cast (const struct rust_op *expr, const struct rust_op *type)
1686 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1688 result->opcode = UNOP_CAST;
1689 result->left.op = expr;
1690 result->right.op = type;
1695 /* Make a call-like operation. This is nominally a function call, but
1696 when lowering we may discover that it actually represents the
1697 creation of a tuple struct. */
1699 static const struct rust_op *
1700 ast_call_ish (enum exp_opcode opcode, const struct rust_op *expr,
1701 VEC (rust_op_ptr) **params)
1703 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1705 result->opcode = opcode;
1706 result->left.op = expr;
1707 result->right.params = params;
1712 /* Make a structure creation operation. */
1714 static const struct rust_op *
1715 ast_struct (const struct rust_op *name, VEC (set_field) **fields)
1717 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1719 result->opcode = OP_AGGREGATE;
1720 result->left.op = name;
1721 result->right.field_inits = fields;
1726 /* Make an identifier path. */
1728 static const struct rust_op *
1729 ast_path (struct stoken path, VEC (rust_op_ptr) **params)
1731 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1733 result->opcode = OP_VAR_VALUE;
1734 result->left.sval = path;
1735 result->right.params = params;
1740 /* Make a string constant operation. */
1742 static const struct rust_op *
1743 ast_string (struct stoken str)
1745 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1747 result->opcode = OP_STRING;
1748 result->left.sval = str;
1753 /* Make a field expression. */
1755 static const struct rust_op *
1756 ast_structop (const struct rust_op *left, const char *name, int completing)
1758 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1760 result->opcode = STRUCTOP_STRUCT;
1761 result->completing = completing;
1762 result->left.op = left;
1763 result->right.sval = make_stoken (name);
1768 /* Make an anonymous struct operation, like 'x.0'. */
1770 static const struct rust_op *
1771 ast_structop_anonymous (const struct rust_op *left,
1772 struct typed_val_int number)
1774 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1776 result->opcode = STRUCTOP_ANONYMOUS;
1777 result->left.op = left;
1778 result->right.typed_val_int = number;
1783 /* Make a range operation. */
1785 static const struct rust_op *
1786 ast_range (const struct rust_op *lhs, const struct rust_op *rhs)
1788 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1790 result->opcode = OP_F90_RANGE;
1791 result->left.op = lhs;
1792 result->right.op = rhs;
1797 /* A helper function to make a type-related AST node. */
1799 static struct rust_op *
1800 ast_basic_type (enum type_code typecode)
1802 struct rust_op *result = OBSTACK_ZALLOC (&work_obstack, struct rust_op);
1804 result->opcode = OP_TYPE;
1805 result->typecode = typecode;
1809 /* Create an AST node describing an array type. */
1811 static const struct rust_op *
1812 ast_array_type (const struct rust_op *lhs, struct typed_val_int val)
1814 struct rust_op *result = ast_basic_type (TYPE_CODE_ARRAY);
1816 result->left.op = lhs;
1817 result->right.typed_val_int = val;
1821 /* Create an AST node describing a reference type. */
1823 static const struct rust_op *
1824 ast_slice_type (const struct rust_op *type)
1826 /* Use TYPE_CODE_COMPLEX just because it is handy. */
1827 struct rust_op *result = ast_basic_type (TYPE_CODE_COMPLEX);
1829 result->left.op = type;
1833 /* Create an AST node describing a reference type. */
1835 static const struct rust_op *
1836 ast_reference_type (const struct rust_op *type)
1838 struct rust_op *result = ast_basic_type (TYPE_CODE_REF);
1840 result->left.op = type;
1844 /* Create an AST node describing a pointer type. */
1846 static const struct rust_op *
1847 ast_pointer_type (const struct rust_op *type, int is_mut)
1849 struct rust_op *result = ast_basic_type (TYPE_CODE_PTR);
1851 result->left.op = type;
1852 /* For the time being we ignore is_mut. */
1856 /* Create an AST node describing a function type. */
1858 static const struct rust_op *
1859 ast_function_type (const struct rust_op *rtype, VEC (rust_op_ptr) **params)
1861 struct rust_op *result = ast_basic_type (TYPE_CODE_FUNC);
1863 result->left.op = rtype;
1864 result->right.params = params;
1868 /* Create an AST node describing a tuple type. */
1870 static const struct rust_op *
1871 ast_tuple_type (VEC (rust_op_ptr) **params)
1873 struct rust_op *result = ast_basic_type (TYPE_CODE_STRUCT);
1875 result->left.params = params;
1879 /* A helper to appropriately munge NAME and BLOCK depending on the
1880 presence of a leading "::". */
1883 munge_name_and_block (const char **name, const struct block **block)
1885 /* If it is a global reference, skip the current block in favor of
1886 the static block. */
1887 if (strncmp (*name, "::", 2) == 0)
1890 *block = block_static_block (*block);
1894 /* Like lookup_symbol, but handles Rust namespace conventions, and
1895 doesn't require field_of_this_result. */
1897 static struct block_symbol
1898 rust_lookup_symbol (const char *name, const struct block *block,
1899 const domain_enum domain)
1901 struct block_symbol result;
1903 munge_name_and_block (&name, &block);
1905 result = lookup_symbol (name, block, domain, NULL);
1906 if (result.symbol != NULL)
1907 update_innermost_block (result);
1911 /* Look up a type, following Rust namespace conventions. */
1913 static struct type *
1914 rust_lookup_type (const char *name, const struct block *block)
1916 struct block_symbol result;
1919 munge_name_and_block (&name, &block);
1921 result = lookup_symbol (name, block, STRUCT_DOMAIN, NULL);
1922 if (result.symbol != NULL)
1924 update_innermost_block (result);
1925 return SYMBOL_TYPE (result.symbol);
1928 type = lookup_typename (parse_language (pstate), parse_gdbarch (pstate),
1933 /* Last chance, try a built-in type. */
1934 return language_lookup_primitive_type (parse_language (pstate),
1935 parse_gdbarch (pstate),
1939 static struct type *convert_ast_to_type (struct parser_state *state,
1940 const struct rust_op *operation);
1941 static const char *convert_name (struct parser_state *state,
1942 const struct rust_op *operation);
1944 /* Convert a vector of rust_ops representing types to a vector of
1947 static VEC (type_ptr) *
1948 convert_params_to_types (struct parser_state *state, VEC (rust_op_ptr) *params)
1951 const struct rust_op *op;
1952 VEC (type_ptr) *result = NULL;
1953 struct cleanup *cleanup = make_cleanup (VEC_cleanup (type_ptr), &result);
1955 for (i = 0; VEC_iterate (rust_op_ptr, params, i, op); ++i)
1956 VEC_safe_push (type_ptr, result, convert_ast_to_type (state, op));
1958 discard_cleanups (cleanup);
1962 /* Convert a rust_op representing a type to a struct type *. */
1964 static struct type *
1965 convert_ast_to_type (struct parser_state *state,
1966 const struct rust_op *operation)
1968 struct type *type, *result = NULL;
1970 if (operation->opcode == OP_VAR_VALUE)
1972 const char *varname = convert_name (state, operation);
1974 result = rust_lookup_type (varname, expression_context_block);
1976 error (_("No typed name '%s' in current context"), varname);
1980 gdb_assert (operation->opcode == OP_TYPE);
1982 switch (operation->typecode)
1984 case TYPE_CODE_ARRAY:
1985 type = convert_ast_to_type (state, operation->left.op);
1986 if (operation->right.typed_val_int.val < 0)
1987 error (_("Negative array length"));
1988 result = lookup_array_range_type (type, 0,
1989 operation->right.typed_val_int.val - 1);
1992 case TYPE_CODE_COMPLEX:
1994 struct type *usize = rust_type ("usize");
1996 type = convert_ast_to_type (state, operation->left.op);
1997 result = rust_slice_type ("&[*gdb*]", type, usize);
2003 /* For now we treat &x and *x identically. */
2004 type = convert_ast_to_type (state, operation->left.op);
2005 result = lookup_pointer_type (type);
2008 case TYPE_CODE_FUNC:
2010 VEC (type_ptr) *args
2011 = convert_params_to_types (state, *operation->right.params);
2012 struct cleanup *cleanup
2013 = make_cleanup (VEC_cleanup (type_ptr), &args);
2014 struct type **argtypes = NULL;
2016 type = convert_ast_to_type (state, operation->left.op);
2017 if (!VEC_empty (type_ptr, args))
2018 argtypes = VEC_address (type_ptr, args);
2021 = lookup_function_type_with_arguments (type,
2022 VEC_length (type_ptr, args),
2024 result = lookup_pointer_type (result);
2026 do_cleanups (cleanup);
2030 case TYPE_CODE_STRUCT:
2032 VEC (type_ptr) *args
2033 = convert_params_to_types (state, *operation->left.params);
2034 struct cleanup *cleanup
2035 = make_cleanup (VEC_cleanup (type_ptr), &args);
2040 obstack_1grow (&work_obstack, '(');
2041 for (i = 0; VEC_iterate (type_ptr, args, i, type); ++i)
2043 char *type_name = type_to_string (type);
2046 obstack_1grow (&work_obstack, ',');
2047 obstack_grow_str (&work_obstack, type_name);
2052 obstack_grow_str0 (&work_obstack, ")");
2053 name = (const char *) obstack_finish (&work_obstack);
2055 /* We don't allow creating new tuple types (yet), but we do
2056 allow looking up existing tuple types. */
2057 result = rust_lookup_type (name, expression_context_block);
2059 error (_("could not find tuple type '%s'"), name);
2061 do_cleanups (cleanup);
2066 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_type");
2069 gdb_assert (result != NULL);
2073 /* A helper function to turn a rust_op representing a name into a full
2074 name. This applies generic arguments as needed. The returned name
2075 is allocated on the work obstack. */
2078 convert_name (struct parser_state *state, const struct rust_op *operation)
2080 VEC (type_ptr) *types;
2081 struct cleanup *cleanup;
2085 gdb_assert (operation->opcode == OP_VAR_VALUE);
2087 if (operation->right.params == NULL)
2088 return operation->left.sval.ptr;
2090 types = convert_params_to_types (state, *operation->right.params);
2091 cleanup = make_cleanup (VEC_cleanup (type_ptr), &types);
2093 obstack_grow_str (&work_obstack, operation->left.sval.ptr);
2094 obstack_1grow (&work_obstack, '<');
2095 for (i = 0; VEC_iterate (type_ptr, types, i, type); ++i)
2097 char *type_name = type_to_string (type);
2100 obstack_1grow (&work_obstack, ',');
2102 obstack_grow_str (&work_obstack, type_name);
2105 obstack_grow_str0 (&work_obstack, ">");
2107 do_cleanups (cleanup);
2109 return (const char *) obstack_finish (&work_obstack);
2112 static void convert_ast_to_expression (struct parser_state *state,
2113 const struct rust_op *operation,
2114 const struct rust_op *top);
2116 /* A helper function that converts a vec of rust_ops to a gdb
2120 convert_params_to_expression (struct parser_state *state,
2121 VEC (rust_op_ptr) *params,
2122 const struct rust_op *top)
2127 for (i = 0; VEC_iterate (rust_op_ptr, params, i, elem); ++i)
2128 convert_ast_to_expression (state, elem, top);
2131 /* Lower a rust_op to a gdb expression. STATE is the parser state.
2132 OPERATION is the operation to lower. TOP is a pointer to the
2133 top-most operation; it is used to handle the special case where the
2134 top-most expression is an identifier and can be optionally lowered
2138 convert_ast_to_expression (struct parser_state *state,
2139 const struct rust_op *operation,
2140 const struct rust_op *top)
2142 switch (operation->opcode)
2145 write_exp_elt_opcode (state, OP_LONG);
2146 write_exp_elt_type (state, operation->left.typed_val_int.type);
2147 write_exp_elt_longcst (state, operation->left.typed_val_int.val);
2148 write_exp_elt_opcode (state, OP_LONG);
2152 write_exp_elt_opcode (state, OP_DOUBLE);
2153 write_exp_elt_type (state, operation->left.typed_val_float.type);
2154 write_exp_elt_dblcst (state, operation->left.typed_val_float.dval);
2155 write_exp_elt_opcode (state, OP_DOUBLE);
2158 case STRUCTOP_STRUCT:
2160 convert_ast_to_expression (state, operation->left.op, top);
2162 if (operation->completing)
2163 mark_struct_expression (state);
2164 write_exp_elt_opcode (state, STRUCTOP_STRUCT);
2165 write_exp_string (state, operation->right.sval);
2166 write_exp_elt_opcode (state, STRUCTOP_STRUCT);
2170 case STRUCTOP_ANONYMOUS:
2172 convert_ast_to_expression (state, operation->left.op, top);
2174 write_exp_elt_opcode (state, STRUCTOP_ANONYMOUS);
2175 write_exp_elt_longcst (state, operation->right.typed_val_int.val);
2176 write_exp_elt_opcode (state, STRUCTOP_ANONYMOUS);
2182 case UNOP_COMPLEMENT:
2185 convert_ast_to_expression (state, operation->left.op, top);
2186 write_exp_elt_opcode (state, operation->opcode);
2189 case BINOP_SUBSCRIPT:
2196 case BINOP_BITWISE_AND:
2197 case BINOP_BITWISE_IOR:
2198 case BINOP_BITWISE_XOR:
2201 case BINOP_LOGICAL_OR:
2202 case BINOP_LOGICAL_AND:
2204 case BINOP_NOTEQUAL:
2211 convert_ast_to_expression (state, operation->left.op, top);
2212 convert_ast_to_expression (state, operation->right.op, top);
2213 if (operation->compound_assignment)
2215 write_exp_elt_opcode (state, BINOP_ASSIGN_MODIFY);
2216 write_exp_elt_opcode (state, operation->opcode);
2217 write_exp_elt_opcode (state, BINOP_ASSIGN_MODIFY);
2220 write_exp_elt_opcode (state, operation->opcode);
2222 if (operation->compound_assignment
2223 || operation->opcode == BINOP_ASSIGN)
2227 type = language_lookup_primitive_type (parse_language (state),
2228 parse_gdbarch (state),
2231 write_exp_elt_opcode (state, OP_LONG);
2232 write_exp_elt_type (state, type);
2233 write_exp_elt_longcst (state, 0);
2234 write_exp_elt_opcode (state, OP_LONG);
2236 write_exp_elt_opcode (state, BINOP_COMMA);
2242 struct type *type = convert_ast_to_type (state, operation->right.op);
2244 convert_ast_to_expression (state, operation->left.op, top);
2245 write_exp_elt_opcode (state, UNOP_CAST);
2246 write_exp_elt_type (state, type);
2247 write_exp_elt_opcode (state, UNOP_CAST);
2253 if (operation->left.op->opcode == OP_VAR_VALUE)
2256 const char *varname = convert_name (state, operation->left.op);
2258 type = rust_lookup_type (varname, expression_context_block);
2261 /* This is actually a tuple struct expression, not a
2265 VEC (rust_op_ptr) *params = *operation->right.params;
2267 if (TYPE_CODE (type) != TYPE_CODE_NAMESPACE)
2269 if (!rust_tuple_struct_type_p (type))
2270 error (_("Type %s is not a tuple struct"), varname);
2273 VEC_iterate (rust_op_ptr, params, i, elem);
2276 char *cell = get_print_cell ();
2278 xsnprintf (cell, PRINT_CELL_SIZE, "__%d", i);
2279 write_exp_elt_opcode (state, OP_NAME);
2280 write_exp_string (state, make_stoken (cell));
2281 write_exp_elt_opcode (state, OP_NAME);
2283 convert_ast_to_expression (state, elem, top);
2286 write_exp_elt_opcode (state, OP_AGGREGATE);
2287 write_exp_elt_type (state, type);
2288 write_exp_elt_longcst (state,
2289 2 * VEC_length (rust_op_ptr,
2291 write_exp_elt_opcode (state, OP_AGGREGATE);
2296 convert_ast_to_expression (state, operation->left.op, top);
2297 convert_params_to_expression (state, *operation->right.params, top);
2298 write_exp_elt_opcode (state, OP_FUNCALL);
2299 write_exp_elt_longcst (state, VEC_length (rust_op_ptr,
2300 *operation->right.params));
2301 write_exp_elt_longcst (state, OP_FUNCALL);
2306 gdb_assert (operation->left.op == NULL);
2307 convert_params_to_expression (state, *operation->right.params, top);
2308 write_exp_elt_opcode (state, OP_ARRAY);
2309 write_exp_elt_longcst (state, 0);
2310 write_exp_elt_longcst (state, VEC_length (rust_op_ptr,
2311 *operation->right.params) - 1);
2312 write_exp_elt_longcst (state, OP_ARRAY);
2317 struct block_symbol sym;
2318 const char *varname;
2320 if (operation->left.sval.ptr[0] == '$')
2322 write_dollar_variable (state, operation->left.sval);
2326 varname = convert_name (state, operation);
2327 sym = rust_lookup_symbol (varname, expression_context_block,
2329 if (sym.symbol != NULL)
2331 write_exp_elt_opcode (state, OP_VAR_VALUE);
2332 write_exp_elt_block (state, sym.block);
2333 write_exp_elt_sym (state, sym.symbol);
2334 write_exp_elt_opcode (state, OP_VAR_VALUE);
2340 type = rust_lookup_type (varname, expression_context_block);
2342 error (_("No symbol '%s' in current context"), varname);
2344 if (TYPE_CODE (type) == TYPE_CODE_STRUCT
2345 && TYPE_NFIELDS (type) == 0)
2347 /* A unit-like struct. */
2348 write_exp_elt_opcode (state, OP_AGGREGATE);
2349 write_exp_elt_type (state, type);
2350 write_exp_elt_longcst (state, 0);
2351 write_exp_elt_opcode (state, OP_AGGREGATE);
2353 else if (operation == top)
2355 write_exp_elt_opcode (state, OP_TYPE);
2356 write_exp_elt_type (state, type);
2357 write_exp_elt_opcode (state, OP_TYPE);
2368 struct set_field *init;
2369 VEC (set_field) *fields = *operation->right.field_inits;
2374 for (i = 0; VEC_iterate (set_field, fields, i, init); ++i)
2376 if (init->name.ptr != NULL)
2378 write_exp_elt_opcode (state, OP_NAME);
2379 write_exp_string (state, init->name);
2380 write_exp_elt_opcode (state, OP_NAME);
2384 convert_ast_to_expression (state, init->init, top);
2387 if (init->name.ptr == NULL)
2389 /* This is handled differently from Ada in our
2391 write_exp_elt_opcode (state, OP_OTHERS);
2395 name = convert_name (state, operation->left.op);
2396 type = rust_lookup_type (name, expression_context_block);
2398 error (_("Could not find type '%s'"), operation->left.sval.ptr);
2400 if (TYPE_CODE (type) != TYPE_CODE_STRUCT
2401 || rust_tuple_type_p (type)
2402 || rust_tuple_struct_type_p (type))
2403 error (_("Struct expression applied to non-struct type"));
2405 write_exp_elt_opcode (state, OP_AGGREGATE);
2406 write_exp_elt_type (state, type);
2407 write_exp_elt_longcst (state, length);
2408 write_exp_elt_opcode (state, OP_AGGREGATE);
2414 write_exp_elt_opcode (state, OP_STRING);
2415 write_exp_string (state, operation->left.sval);
2416 write_exp_elt_opcode (state, OP_STRING);
2422 enum f90_range_type kind = BOTH_BOUND_DEFAULT;
2424 if (operation->left.op != NULL)
2426 convert_ast_to_expression (state, operation->left.op, top);
2427 kind = HIGH_BOUND_DEFAULT;
2429 if (operation->right.op != NULL)
2431 convert_ast_to_expression (state, operation->right.op, top);
2432 if (kind == BOTH_BOUND_DEFAULT)
2433 kind = LOW_BOUND_DEFAULT;
2436 gdb_assert (kind == HIGH_BOUND_DEFAULT);
2437 kind = NONE_BOUND_DEFAULT;
2440 write_exp_elt_opcode (state, OP_F90_RANGE);
2441 write_exp_elt_longcst (state, kind);
2442 write_exp_elt_opcode (state, OP_F90_RANGE);
2447 gdb_assert_not_reached ("unhandled opcode in convert_ast_to_expression");
2453 /* The parser as exposed to gdb. */
2456 rust_parse (struct parser_state *state)
2459 struct cleanup *cleanup;
2461 obstack_init (&work_obstack);
2462 cleanup = make_cleanup_obstack_free (&work_obstack);
2466 result = rustyyparse ();
2468 if (!result || (parse_completion && rust_ast != NULL))
2470 const struct rust_op *ast = rust_ast;
2473 gdb_assert (ast != NULL);
2474 convert_ast_to_expression (state, ast, ast);
2477 do_cleanups (cleanup);
2481 /* The parser error handler. */
2484 rustyyerror (char *msg)
2486 const char *where = prev_lexptr ? prev_lexptr : lexptr;
2487 error (_("%s in expression, near `%s'."), (msg ? msg : "Error"), where);
2494 /* Initialize the lexer for testing. */
2497 rust_lex_test_init (const char *input)
2504 /* A test helper that lexes a string, expecting a single token. It
2505 returns the lexer data for this token. */
2508 rust_lex_test_one (const char *input, int expected)
2513 rust_lex_test_init (input);
2515 token = rustyylex ();
2516 SELF_CHECK (token == expected);
2517 result = rustyylval;
2521 token = rustyylex ();
2522 SELF_CHECK (token == 0);
2528 /* Test that INPUT lexes as the integer VALUE. */
2531 rust_lex_int_test (const char *input, int value, int kind)
2533 RUSTSTYPE result = rust_lex_test_one (input, kind);
2534 SELF_CHECK (result.typed_val_int.val == value);
2537 /* Test that INPUT throws an exception with text ERR. */
2540 rust_lex_exception_test (const char *input, const char *err)
2544 /* The "kind" doesn't matter. */
2545 rust_lex_test_one (input, DECIMAL_INTEGER);
2548 CATCH (except, RETURN_MASK_ERROR)
2550 SELF_CHECK (strcmp (except.message, err) == 0);
2555 /* Test that INPUT lexes as the identifier, string, or byte-string
2556 VALUE. KIND holds the expected token kind. */
2559 rust_lex_stringish_test (const char *input, const char *value, int kind)
2561 RUSTSTYPE result = rust_lex_test_one (input, kind);
2562 SELF_CHECK (result.sval.length == strlen (value));
2563 SELF_CHECK (strncmp (result.sval.ptr, value, result.sval.length) == 0);
2566 /* Helper to test that a string parses as a given token sequence. */
2569 rust_lex_test_sequence (const char *input, int len, const int expected[])
2576 for (i = 0; i < len; ++i)
2578 int token = rustyylex ();
2580 SELF_CHECK (token == expected[i]);
2584 /* Tests for an integer-parsing corner case. */
2587 rust_lex_test_trailing_dot (void)
2589 const int expected1[] = { DECIMAL_INTEGER, '.', IDENT, '(', ')', 0 };
2590 const int expected2[] = { INTEGER, '.', IDENT, '(', ')', 0 };
2591 const int expected3[] = { FLOAT, EQEQ, '(', ')', 0 };
2592 const int expected4[] = { DECIMAL_INTEGER, DOTDOT, DECIMAL_INTEGER, 0 };
2594 rust_lex_test_sequence ("23.g()", ARRAY_SIZE (expected1), expected1);
2595 rust_lex_test_sequence ("23_0.g()", ARRAY_SIZE (expected2), expected2);
2596 rust_lex_test_sequence ("23.==()", ARRAY_SIZE (expected3), expected3);
2597 rust_lex_test_sequence ("23..25", ARRAY_SIZE (expected4), expected4);
2600 /* Tests of completion. */
2603 rust_lex_test_completion (void)
2605 const int expected[] = { IDENT, '.', COMPLETE, 0 };
2607 parse_completion = 1;
2609 rust_lex_test_sequence ("something.wha", ARRAY_SIZE (expected), expected);
2610 rust_lex_test_sequence ("something.", ARRAY_SIZE (expected), expected);
2612 parse_completion = 0;
2615 /* Test pushback. */
2618 rust_lex_test_push_back (void)
2622 rust_lex_test_init (">>=");
2624 token = rustyylex ();
2625 SELF_CHECK (token == COMPOUND_ASSIGN);
2626 SELF_CHECK (rustyylval.opcode == BINOP_RSH);
2628 rust_push_back ('=');
2630 token = rustyylex ();
2631 SELF_CHECK (token == '=');
2633 token = rustyylex ();
2634 SELF_CHECK (token == 0);
2637 /* Unit test the lexer. */
2640 rust_lex_tests (void)
2644 obstack_init (&work_obstack);
2647 rust_lex_test_one ("", 0);
2648 rust_lex_test_one (" \t \n \r ", 0);
2649 rust_lex_test_one ("thread 23", 0);
2650 rust_lex_test_one ("task 23", 0);
2651 rust_lex_test_one ("th 104", 0);
2652 rust_lex_test_one ("ta 97", 0);
2654 rust_lex_int_test ("'z'", 'z', INTEGER);
2655 rust_lex_int_test ("'\\xff'", 0xff, INTEGER);
2656 rust_lex_int_test ("'\\u{1016f}'", 0x1016f, INTEGER);
2657 rust_lex_int_test ("b'z'", 'z', INTEGER);
2658 rust_lex_int_test ("b'\\xfe'", 0xfe, INTEGER);
2659 rust_lex_int_test ("b'\\xFE'", 0xfe, INTEGER);
2660 rust_lex_int_test ("b'\\xfE'", 0xfe, INTEGER);
2662 /* Test all escapes in both modes. */
2663 rust_lex_int_test ("'\\n'", '\n', INTEGER);
2664 rust_lex_int_test ("'\\r'", '\r', INTEGER);
2665 rust_lex_int_test ("'\\t'", '\t', INTEGER);
2666 rust_lex_int_test ("'\\\\'", '\\', INTEGER);
2667 rust_lex_int_test ("'\\0'", '\0', INTEGER);
2668 rust_lex_int_test ("'\\''", '\'', INTEGER);
2669 rust_lex_int_test ("'\\\"'", '"', INTEGER);
2671 rust_lex_int_test ("b'\\n'", '\n', INTEGER);
2672 rust_lex_int_test ("b'\\r'", '\r', INTEGER);
2673 rust_lex_int_test ("b'\\t'", '\t', INTEGER);
2674 rust_lex_int_test ("b'\\\\'", '\\', INTEGER);
2675 rust_lex_int_test ("b'\\0'", '\0', INTEGER);
2676 rust_lex_int_test ("b'\\''", '\'', INTEGER);
2677 rust_lex_int_test ("b'\\\"'", '"', INTEGER);
2679 rust_lex_exception_test ("'z", "Unterminated character literal");
2680 rust_lex_exception_test ("b'\\x0'", "Not enough hex digits seen");
2681 rust_lex_exception_test ("b'\\u{0}'", "Unicode escape in byte literal");
2682 rust_lex_exception_test ("'\\x0'", "Not enough hex digits seen");
2683 rust_lex_exception_test ("'\\u0'", "Missing '{' in Unicode escape");
2684 rust_lex_exception_test ("'\\u{0", "Missing '}' in Unicode escape");
2685 rust_lex_exception_test ("'\\u{0000007}", "Overlong hex escape");
2686 rust_lex_exception_test ("'\\u{}", "Not enough hex digits seen");
2687 rust_lex_exception_test ("'\\Q'", "Invalid escape \\Q in literal");
2688 rust_lex_exception_test ("b'\\Q'", "Invalid escape \\Q in literal");
2690 rust_lex_int_test ("23", 23, DECIMAL_INTEGER);
2691 rust_lex_int_test ("2_344__29", 234429, INTEGER);
2692 rust_lex_int_test ("0x1f", 0x1f, INTEGER);
2693 rust_lex_int_test ("23usize", 23, INTEGER);
2694 rust_lex_int_test ("23i32", 23, INTEGER);
2695 rust_lex_int_test ("0x1_f", 0x1f, INTEGER);
2696 rust_lex_int_test ("0b1_101011__", 0x6b, INTEGER);
2697 rust_lex_int_test ("0o001177i64", 639, INTEGER);
2699 rust_lex_test_trailing_dot ();
2701 rust_lex_test_one ("23.", FLOAT);
2702 rust_lex_test_one ("23.99f32", FLOAT);
2703 rust_lex_test_one ("23e7", FLOAT);
2704 rust_lex_test_one ("23E-7", FLOAT);
2705 rust_lex_test_one ("23e+7", FLOAT);
2706 rust_lex_test_one ("23.99e+7f64", FLOAT);
2707 rust_lex_test_one ("23.82f32", FLOAT);
2709 rust_lex_stringish_test ("hibob", "hibob", IDENT);
2710 rust_lex_stringish_test ("hibob__93", "hibob__93", IDENT);
2711 rust_lex_stringish_test ("thread", "thread", IDENT);
2713 rust_lex_stringish_test ("\"string\"", "string", STRING);
2714 rust_lex_stringish_test ("\"str\\ting\"", "str\ting", STRING);
2715 rust_lex_stringish_test ("\"str\\\"ing\"", "str\"ing", STRING);
2716 rust_lex_stringish_test ("r\"str\\ing\"", "str\\ing", STRING);
2717 rust_lex_stringish_test ("r#\"str\\ting\"#", "str\\ting", STRING);
2718 rust_lex_stringish_test ("r###\"str\\\"ing\"###", "str\\\"ing", STRING);
2720 rust_lex_stringish_test ("b\"string\"", "string", BYTESTRING);
2721 rust_lex_stringish_test ("b\"\x73tring\"", "string", BYTESTRING);
2722 rust_lex_stringish_test ("b\"str\\\"ing\"", "str\"ing", BYTESTRING);
2723 rust_lex_stringish_test ("br####\"\\x73tring\"####", "\\x73tring",
2726 for (i = 0; i < ARRAY_SIZE (identifier_tokens); ++i)
2727 rust_lex_test_one (identifier_tokens[i].name, identifier_tokens[i].value);
2729 for (i = 0; i < ARRAY_SIZE (operator_tokens); ++i)
2730 rust_lex_test_one (operator_tokens[i].name, operator_tokens[i].value);
2732 rust_lex_test_completion ();
2733 rust_lex_test_push_back ();
2735 obstack_free (&work_obstack, NULL);
2739 #endif /* GDB_SELF_TEST */
2742 _initialize_rust_exp (void)
2744 int code = regcomp (&number_regex, number_regex_text, REG_EXTENDED);
2745 /* If the regular expression was incorrect, it was a programming
2747 gdb_assert (code == 0);
2750 register_self_test (rust_lex_tests);