1 /* Rust expression parsing for GDB, the GNU debugger.
3 Copyright (C) 2016-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
23 #include "cp-support.h"
24 #include "gdbsupport/gdb_obstack.h"
25 #include "gdbsupport/gdb_regex.h"
26 #include "rust-lang.h"
27 #include "parser-defs.h"
28 #include "gdbsupport/selftest.h"
36 /* A regular expression for matching Rust numbers. This is split up
37 since it is very long and this gives us a way to comment the
40 static const char number_regex_text
[] =
41 /* subexpression 1: allows use of alternation, otherwise uninteresting */
43 /* First comes floating point. */
44 /* Recognize number after the decimal point, with optional
45 exponent and optional type suffix.
46 subexpression 2: allows "?", otherwise uninteresting
47 subexpression 3: if present, type suffix
49 "[0-9][0-9_]*\\.[0-9][0-9_]*([eE][-+]?[0-9][0-9_]*)?(f32|f64)?"
52 /* Recognize exponent without decimal point, with optional type
54 subexpression 4: if present, type suffix
57 "[0-9][0-9_]*[eE][-+]?[0-9][0-9_]*(f32|f64)?"
59 /* "23." is a valid floating point number, but "23.e5" and
60 "23.f32" are not. So, handle the trailing-. case
64 /* Finally come integers.
65 subexpression 5: text of integer
66 subexpression 6: if present, type suffix
67 subexpression 7: allows use of alternation, otherwise uninteresting
71 "(0x[a-fA-F0-9_]+|0o[0-7_]+|0b[01_]+|[0-9][0-9_]*)"
72 "([iu](size|8|16|32|64|128))?"
74 /* The number of subexpressions to allocate space for, including the
75 "0th" whole match subexpression. */
76 #define NUM_SUBEXPRESSIONS 8
78 /* The compiled number-matching regex. */
80 static regex_t number_regex
;
82 /* The kinds of tokens. Note that single-character tokens are
83 represented by themselves, so for instance '[' is a token. */
86 /* Make sure to start after any ASCII character. */
110 /* Operator tokens. */
125 /* A typed integer constant. */
133 /* A typed floating point constant. */
135 struct typed_val_float
141 /* A struct of this type is used to describe a token. */
147 enum exp_opcode opcode
;
150 /* Identifier tokens. */
152 static const struct token_info identifier_tokens
[] =
154 { "as", KW_AS
, OP_NULL
},
155 { "false", KW_FALSE
, OP_NULL
},
156 { "if", 0, OP_NULL
},
157 { "mut", KW_MUT
, OP_NULL
},
158 { "const", KW_CONST
, OP_NULL
},
159 { "self", KW_SELF
, OP_NULL
},
160 { "super", KW_SUPER
, OP_NULL
},
161 { "true", KW_TRUE
, OP_NULL
},
162 { "extern", KW_EXTERN
, OP_NULL
},
163 { "fn", KW_FN
, OP_NULL
},
164 { "sizeof", KW_SIZEOF
, OP_NULL
},
167 /* Operator tokens, sorted longest first. */
169 static const struct token_info operator_tokens
[] =
171 { ">>=", COMPOUND_ASSIGN
, BINOP_RSH
},
172 { "<<=", COMPOUND_ASSIGN
, BINOP_LSH
},
174 { "<<", LSH
, OP_NULL
},
175 { ">>", RSH
, OP_NULL
},
176 { "&&", ANDAND
, OP_NULL
},
177 { "||", OROR
, OP_NULL
},
178 { "==", EQEQ
, OP_NULL
},
179 { "!=", NOTEQ
, OP_NULL
},
180 { "<=", LTEQ
, OP_NULL
},
181 { ">=", GTEQ
, OP_NULL
},
182 { "+=", COMPOUND_ASSIGN
, BINOP_ADD
},
183 { "-=", COMPOUND_ASSIGN
, BINOP_SUB
},
184 { "*=", COMPOUND_ASSIGN
, BINOP_MUL
},
185 { "/=", COMPOUND_ASSIGN
, BINOP_DIV
},
186 { "%=", COMPOUND_ASSIGN
, BINOP_REM
},
187 { "&=", COMPOUND_ASSIGN
, BINOP_BITWISE_AND
},
188 { "|=", COMPOUND_ASSIGN
, BINOP_BITWISE_IOR
},
189 { "^=", COMPOUND_ASSIGN
, BINOP_BITWISE_XOR
},
190 { "..=", DOTDOTEQ
, OP_NULL
},
192 { "::", COLONCOLON
, OP_NULL
},
193 { "..", DOTDOT
, OP_NULL
},
194 { "->", ARROW
, OP_NULL
}
197 /* An instance of this is created before parsing, and destroyed when
198 parsing is finished. */
202 explicit rust_parser (struct parser_state
*state
)
207 DISABLE_COPY_AND_ASSIGN (rust_parser
);
209 /* Return the parser's language. */
210 const struct language_defn
*language () const
212 return pstate
->language ();
215 /* Return the parser's gdbarch. */
216 struct gdbarch
*arch () const
218 return pstate
->gdbarch ();
221 /* A helper to look up a Rust type, or fail. This only works for
222 types defined by rust_language_arch_info. */
224 struct type
*get_type (const char *name
)
228 type
= language_lookup_primitive_type (language (), arch (), name
);
230 error (_("Could not find Rust type %s"), name
);
234 std::string
crate_name (const std::string
&name
);
235 std::string
super_name (const std::string
&ident
, unsigned int n_supers
);
237 int lex_character ();
240 int lex_identifier ();
241 uint32_t lex_hex (int min
, int max
);
242 uint32_t lex_escape (int is_byte
);
244 int lex_one_token ();
245 void push_back (char c
);
247 /* The main interface to lexing. Lexes one token and updates the
251 current_token
= lex_one_token ();
254 /* Assuming the current token is TYPE, lex the next token. */
255 void assume (int type
)
257 gdb_assert (current_token
== type
);
261 /* Require the single-character token C, and lex the next token; or
262 throw an exception. */
263 void require (char type
)
265 if (current_token
!= type
)
266 error (_("'%c' expected"), type
);
270 /* Entry point for all parsing. */
271 operation_up
parse_entry_point ()
274 operation_up result
= parse_expr ();
275 if (current_token
!= 0)
276 error (_("Syntax error near '%s'"), pstate
->prev_lexptr
);
280 operation_up
parse_tuple ();
281 operation_up
parse_array ();
282 operation_up
name_to_operation (const std::string
&name
);
283 operation_up
parse_struct_expr (struct type
*type
);
284 operation_up
parse_binop (bool required
);
285 operation_up
parse_range ();
286 operation_up
parse_expr ();
287 operation_up
parse_sizeof ();
288 operation_up
parse_addr ();
289 operation_up
parse_field (operation_up
&&);
290 operation_up
parse_index (operation_up
&&);
291 std::vector
<operation_up
> parse_paren_args ();
292 operation_up
parse_call (operation_up
&&);
293 std::vector
<struct type
*> parse_type_list ();
294 std::vector
<struct type
*> parse_maybe_type_list ();
295 struct type
*parse_array_type ();
296 struct type
*parse_slice_type ();
297 struct type
*parse_pointer_type ();
298 struct type
*parse_function_type ();
299 struct type
*parse_tuple_type ();
300 struct type
*parse_type ();
301 std::string
parse_path (bool for_expr
);
302 operation_up
parse_string ();
303 operation_up
parse_tuple_struct (struct type
*type
);
304 operation_up
parse_path_expr ();
305 operation_up
parse_atom (bool required
);
307 void update_innermost_block (struct block_symbol sym
);
308 struct block_symbol
lookup_symbol (const char *name
,
309 const struct block
*block
,
310 const domain_search_flags domain
);
311 struct type
*rust_lookup_type (const char *name
);
313 /* Clear some state. This is only used for testing. */
315 void reset (const char *input
)
317 pstate
->prev_lexptr
= nullptr;
318 pstate
->lexptr
= input
;
321 current_int_val
= {};
322 current_float_val
= {};
323 current_string_val
= {};
324 current_opcode
= OP_NULL
;
326 #endif /* GDB_SELF_TEST */
328 /* Return the token's string value as a string. */
329 std::string
get_string () const
331 return std::string (current_string_val
.ptr
, current_string_val
.length
);
334 /* A pointer to this is installed globally. */
335 auto_obstack obstack
;
337 /* The parser state gdb gave us. */
338 struct parser_state
*pstate
;
340 /* Depth of parentheses. */
343 /* The current token's type. */
344 int current_token
= 0;
345 /* The current token's payload, if any. */
346 typed_val_int current_int_val
{};
347 typed_val_float current_float_val
{};
348 struct stoken current_string_val
{};
349 enum exp_opcode current_opcode
= OP_NULL
;
351 /* When completing, this may be set to the field operation to
353 operation_up completion_op
;
356 /* Return an string referring to NAME, but relative to the crate's
360 rust_parser::crate_name (const std::string
&name
)
362 std::string crate
= rust_crate_for_block (pstate
->expression_context_block
);
365 error (_("Could not find crate for current location"));
366 return "::" + crate
+ "::" + name
;
369 /* Return a string referring to a "super::" qualified name. IDENT is
370 the base name and N_SUPERS is how many "super::"s were provided.
371 N_SUPERS can be zero. */
374 rust_parser::super_name (const std::string
&ident
, unsigned int n_supers
)
376 const char *scope
= "";
377 if (pstate
->expression_context_block
!= nullptr)
378 scope
= pstate
->expression_context_block
->scope ();
381 if (scope
[0] == '\0')
382 error (_("Couldn't find namespace scope for self::"));
387 std::vector
<int> offsets
;
388 unsigned int current_len
;
390 current_len
= cp_find_first_component (scope
);
391 while (scope
[current_len
] != '\0')
393 offsets
.push_back (current_len
);
394 gdb_assert (scope
[current_len
] == ':');
397 current_len
+= cp_find_first_component (scope
401 len
= offsets
.size ();
403 error (_("Too many super:: uses from '%s'"), scope
);
405 offset
= offsets
[len
- n_supers
];
408 offset
= strlen (scope
);
410 return "::" + std::string (scope
, offset
) + "::" + ident
;
413 /* A helper to appropriately munge NAME and BLOCK depending on the
414 presence of a leading "::". */
417 munge_name_and_block (const char **name
, const struct block
**block
)
419 /* If it is a global reference, skip the current block in favor of
421 if (startswith (*name
, "::"))
424 *block
= (*block
)->static_block ();
428 /* Like lookup_symbol, but handles Rust namespace conventions, and
429 doesn't require field_of_this_result. */
432 rust_parser::lookup_symbol (const char *name
, const struct block
*block
,
433 const domain_search_flags domain
)
435 struct block_symbol result
;
437 munge_name_and_block (&name
, &block
);
439 result
= ::lookup_symbol (name
, block
, domain
, NULL
);
440 if (result
.symbol
!= NULL
)
441 update_innermost_block (result
);
445 /* Look up a type, following Rust namespace conventions. */
448 rust_parser::rust_lookup_type (const char *name
)
450 struct block_symbol result
;
453 const struct block
*block
= pstate
->expression_context_block
;
454 munge_name_and_block (&name
, &block
);
456 result
= ::lookup_symbol (name
, block
, SEARCH_TYPE_DOMAIN
, nullptr);
457 if (result
.symbol
!= NULL
)
459 update_innermost_block (result
);
460 return result
.symbol
->type ();
463 type
= lookup_typename (language (), name
, NULL
, 1);
467 /* Last chance, try a built-in type. */
468 return language_lookup_primitive_type (language (), arch (), name
);
471 /* A helper that updates the innermost block as appropriate. */
474 rust_parser::update_innermost_block (struct block_symbol sym
)
476 if (symbol_read_needs_frame (sym
.symbol
))
477 pstate
->block_tracker
->update (sym
);
480 /* Lex a hex number with at least MIN digits and at most MAX
484 rust_parser::lex_hex (int min
, int max
)
488 /* We only want to stop at MAX if we're lexing a byte escape. */
489 int check_max
= min
== max
;
491 while ((check_max
? len
<= max
: 1)
492 && ((pstate
->lexptr
[0] >= 'a' && pstate
->lexptr
[0] <= 'f')
493 || (pstate
->lexptr
[0] >= 'A' && pstate
->lexptr
[0] <= 'F')
494 || (pstate
->lexptr
[0] >= '0' && pstate
->lexptr
[0] <= '9')))
497 if (pstate
->lexptr
[0] >= 'a' && pstate
->lexptr
[0] <= 'f')
498 result
= result
+ 10 + pstate
->lexptr
[0] - 'a';
499 else if (pstate
->lexptr
[0] >= 'A' && pstate
->lexptr
[0] <= 'F')
500 result
= result
+ 10 + pstate
->lexptr
[0] - 'A';
502 result
= result
+ pstate
->lexptr
[0] - '0';
508 error (_("Not enough hex digits seen"));
511 gdb_assert (min
!= max
);
512 error (_("Overlong hex escape"));
518 /* Lex an escape. IS_BYTE is true if we're lexing a byte escape;
519 otherwise we're lexing a character escape. */
522 rust_parser::lex_escape (int is_byte
)
526 gdb_assert (pstate
->lexptr
[0] == '\\');
528 switch (pstate
->lexptr
[0])
532 result
= lex_hex (2, 2);
537 error (_("Unicode escape in byte literal"));
539 if (pstate
->lexptr
[0] != '{')
540 error (_("Missing '{' in Unicode escape"));
542 result
= lex_hex (1, 6);
543 /* Could do range checks here. */
544 if (pstate
->lexptr
[0] != '}')
545 error (_("Missing '}' in Unicode escape"));
579 error (_("Invalid escape \\%c in literal"), pstate
->lexptr
[0]);
585 /* A helper for lex_character. Search forward for the closing single
586 quote, then convert the bytes from the host charset to UTF-32. */
589 lex_multibyte_char (const char *text
, int *len
)
591 /* Only look a maximum of 5 bytes for the closing quote. This is
592 the maximum for UTF-8. */
594 gdb_assert (text
[0] != '\'');
595 for (quote
= 1; text
[quote
] != '\0' && text
[quote
] != '\''; ++quote
)
598 /* The caller will issue an error. */
599 if (text
[quote
] == '\0')
603 convert_between_encodings (host_charset (), HOST_UTF32
,
604 (const gdb_byte
*) text
,
605 quote
, 1, &result
, translit_none
);
607 int size
= obstack_object_size (&result
);
609 error (_("overlong character literal"));
611 memcpy (&value
, obstack_finish (&result
), size
);
615 /* Lex a character constant. */
618 rust_parser::lex_character ()
623 if (pstate
->lexptr
[0] == 'b')
628 gdb_assert (pstate
->lexptr
[0] == '\'');
630 if (pstate
->lexptr
[0] == '\'')
631 error (_("empty character literal"));
632 else if (pstate
->lexptr
[0] == '\\')
633 value
= lex_escape (is_byte
);
637 value
= lex_multibyte_char (&pstate
->lexptr
[0], &len
);
638 pstate
->lexptr
+= len
;
641 if (pstate
->lexptr
[0] != '\'')
642 error (_("Unterminated character literal"));
645 current_int_val
.val
= value
;
646 current_int_val
.type
= get_type (is_byte
? "u8" : "char");
651 /* Return the offset of the double quote if STR looks like the start
652 of a raw string, or 0 if STR does not start a raw string. */
655 starts_raw_string (const char *str
)
657 const char *save
= str
;
662 while (str
[0] == '#')
669 /* Return true if STR looks like the end of a raw string that had N
670 hashes at the start. */
673 ends_raw_string (const char *str
, int n
)
677 gdb_assert (str
[0] == '"');
678 for (i
= 0; i
< n
; ++i
)
679 if (str
[i
+ 1] != '#')
684 /* Lex a string constant. */
687 rust_parser::lex_string ()
689 int is_byte
= pstate
->lexptr
[0] == 'b';
694 raw_length
= starts_raw_string (pstate
->lexptr
);
695 pstate
->lexptr
+= raw_length
;
696 gdb_assert (pstate
->lexptr
[0] == '"');
705 if (pstate
->lexptr
[0] == '"' && ends_raw_string (pstate
->lexptr
,
708 /* Exit with lexptr pointing after the final "#". */
709 pstate
->lexptr
+= raw_length
;
712 else if (pstate
->lexptr
[0] == '\0')
713 error (_("Unexpected EOF in string"));
715 value
= pstate
->lexptr
[0] & 0xff;
716 if (is_byte
&& value
> 127)
717 error (_("Non-ASCII value in raw byte string"));
718 obstack_1grow (&obstack
, value
);
722 else if (pstate
->lexptr
[0] == '"')
724 /* Make sure to skip the quote. */
728 else if (pstate
->lexptr
[0] == '\\')
730 value
= lex_escape (is_byte
);
733 obstack_1grow (&obstack
, value
);
735 convert_between_encodings (HOST_UTF32
, "UTF-8",
737 sizeof (value
), sizeof (value
),
738 &obstack
, translit_none
);
740 else if (pstate
->lexptr
[0] == '\0')
741 error (_("Unexpected EOF in string"));
744 value
= pstate
->lexptr
[0] & 0xff;
745 if (is_byte
&& value
> 127)
746 error (_("Non-ASCII value in byte string"));
747 obstack_1grow (&obstack
, value
);
752 current_string_val
.length
= obstack_object_size (&obstack
);
753 current_string_val
.ptr
= (const char *) obstack_finish (&obstack
);
754 return is_byte
? BYTESTRING
: STRING
;
757 /* Return true if STRING starts with whitespace followed by a digit. */
760 space_then_number (const char *string
)
762 const char *p
= string
;
764 while (p
[0] == ' ' || p
[0] == '\t')
769 return *p
>= '0' && *p
<= '9';
772 /* Return true if C can start an identifier. */
775 rust_identifier_start_p (char c
)
777 return ((c
>= 'a' && c
<= 'z')
778 || (c
>= 'A' && c
<= 'Z')
781 /* Allow any non-ASCII character as an identifier. There
782 doesn't seem to be a need to be picky about this. */
786 /* Lex an identifier. */
789 rust_parser::lex_identifier ()
792 const struct token_info
*token
;
793 int is_gdb_var
= pstate
->lexptr
[0] == '$';
796 if (pstate
->lexptr
[0] == 'r'
797 && pstate
->lexptr
[1] == '#'
798 && rust_identifier_start_p (pstate
->lexptr
[2]))
804 const char *start
= pstate
->lexptr
;
805 gdb_assert (rust_identifier_start_p (pstate
->lexptr
[0]));
809 /* Allow any non-ASCII character here. This "handles" UTF-8 by
810 passing it through. */
811 while ((pstate
->lexptr
[0] >= 'a' && pstate
->lexptr
[0] <= 'z')
812 || (pstate
->lexptr
[0] >= 'A' && pstate
->lexptr
[0] <= 'Z')
813 || pstate
->lexptr
[0] == '_'
814 || (is_gdb_var
&& pstate
->lexptr
[0] == '$')
815 || (pstate
->lexptr
[0] >= '0' && pstate
->lexptr
[0] <= '9')
816 || (pstate
->lexptr
[0] & 0x80) != 0)
820 length
= pstate
->lexptr
- start
;
824 for (const auto &candidate
: identifier_tokens
)
826 if (length
== strlen (candidate
.name
)
827 && strncmp (candidate
.name
, start
, length
) == 0)
837 if (token
->value
== 0)
839 /* Leave the terminating token alone. */
840 pstate
->lexptr
= start
;
844 else if (token
== NULL
846 && (strncmp (start
, "thread", length
) == 0
847 || strncmp (start
, "task", length
) == 0)
848 && space_then_number (pstate
->lexptr
))
850 /* "task" or "thread" followed by a number terminates the
851 parse, per gdb rules. */
852 pstate
->lexptr
= start
;
856 if (token
== NULL
|| (pstate
->parse_completion
&& pstate
->lexptr
[0] == '\0'))
858 current_string_val
.length
= length
;
859 current_string_val
.ptr
= start
;
862 if (pstate
->parse_completion
&& pstate
->lexptr
[0] == '\0')
864 /* Prevent rustyylex from returning two COMPLETE tokens. */
865 pstate
->prev_lexptr
= pstate
->lexptr
;
876 /* Lex an operator. */
879 rust_parser::lex_operator ()
881 const struct token_info
*token
= NULL
;
883 for (const auto &candidate
: operator_tokens
)
885 if (strncmp (candidate
.name
, pstate
->lexptr
,
886 strlen (candidate
.name
)) == 0)
888 pstate
->lexptr
+= strlen (candidate
.name
);
896 current_opcode
= token
->opcode
;
900 return *pstate
->lexptr
++;
906 rust_parser::lex_number ()
908 regmatch_t subexps
[NUM_SUBEXPRESSIONS
];
911 int could_be_decimal
= 1;
912 int implicit_i32
= 0;
913 const char *type_name
= NULL
;
919 match
= regexec (&number_regex
, pstate
->lexptr
, ARRAY_SIZE (subexps
),
921 /* Failure means the regexp is broken. */
922 gdb_assert (match
== 0);
924 if (subexps
[INT_TEXT
].rm_so
!= -1)
926 /* Integer part matched. */
928 end_index
= subexps
[INT_TEXT
].rm_eo
;
929 if (subexps
[INT_TYPE
].rm_so
== -1)
936 type_index
= INT_TYPE
;
937 could_be_decimal
= 0;
940 else if (subexps
[FLOAT_TYPE1
].rm_so
!= -1)
942 /* Found floating point type suffix. */
943 end_index
= subexps
[FLOAT_TYPE1
].rm_so
;
944 type_index
= FLOAT_TYPE1
;
946 else if (subexps
[FLOAT_TYPE2
].rm_so
!= -1)
948 /* Found floating point type suffix. */
949 end_index
= subexps
[FLOAT_TYPE2
].rm_so
;
950 type_index
= FLOAT_TYPE2
;
954 /* Any other floating point match. */
955 end_index
= subexps
[0].rm_eo
;
959 /* We need a special case if the final character is ".". In this
960 case we might need to parse an integer. For example, "23.f()" is
961 a request for a trait method call, not a syntax error involving
962 the floating point number "23.". */
963 gdb_assert (subexps
[0].rm_eo
> 0);
964 if (pstate
->lexptr
[subexps
[0].rm_eo
- 1] == '.')
966 const char *next
= skip_spaces (&pstate
->lexptr
[subexps
[0].rm_eo
]);
968 if (rust_identifier_start_p (*next
) || *next
== '.')
972 end_index
= subexps
[0].rm_eo
;
974 could_be_decimal
= 1;
979 /* Compute the type name if we haven't already. */
980 std::string type_name_holder
;
981 if (type_name
== NULL
)
983 gdb_assert (type_index
!= -1);
984 type_name_holder
= std::string ((pstate
->lexptr
985 + subexps
[type_index
].rm_so
),
986 (subexps
[type_index
].rm_eo
987 - subexps
[type_index
].rm_so
));
988 type_name
= type_name_holder
.c_str ();
991 /* Look up the type. */
992 type
= get_type (type_name
);
994 /* Copy the text of the number and remove the "_"s. */
996 for (i
= 0; i
< end_index
&& pstate
->lexptr
[i
]; ++i
)
998 if (pstate
->lexptr
[i
] == '_')
999 could_be_decimal
= 0;
1001 number
.push_back (pstate
->lexptr
[i
]);
1004 /* Advance past the match. */
1005 pstate
->lexptr
+= subexps
[0].rm_eo
;
1007 /* Parse the number. */
1013 if (number
[0] == '0')
1015 if (number
[1] == 'x')
1017 else if (number
[1] == 'o')
1019 else if (number
[1] == 'b')
1024 could_be_decimal
= 0;
1028 if (!current_int_val
.val
.set (number
.c_str () + offset
, radix
))
1030 /* Shouldn't be possible. */
1031 error (_("Invalid integer"));
1035 static gdb_mpz sixty_three_bit
= gdb_mpz::pow (2, 63);
1036 static gdb_mpz thirty_one_bit
= gdb_mpz::pow (2, 31);
1038 if (current_int_val
.val
>= sixty_three_bit
)
1039 type
= get_type ("i128");
1040 else if (current_int_val
.val
>= thirty_one_bit
)
1041 type
= get_type ("i64");
1044 current_int_val
.type
= type
;
1048 current_float_val
.type
= type
;
1049 bool parsed
= parse_float (number
.c_str (), number
.length (),
1050 current_float_val
.type
,
1051 current_float_val
.val
.data ());
1052 gdb_assert (parsed
);
1055 return is_integer
? (could_be_decimal
? DECIMAL_INTEGER
: INTEGER
) : FLOAT
;
1061 rust_parser::lex_one_token ()
1063 /* Skip all leading whitespace. */
1064 while (pstate
->lexptr
[0] == ' '
1065 || pstate
->lexptr
[0] == '\t'
1066 || pstate
->lexptr
[0] == '\r'
1067 || pstate
->lexptr
[0] == '\n')
1070 /* If we hit EOF and we're completing, then return COMPLETE -- maybe
1071 we're completing an empty string at the end of a field_expr.
1072 But, we don't want to return two COMPLETE tokens in a row. */
1073 if (pstate
->lexptr
[0] == '\0' && pstate
->lexptr
== pstate
->prev_lexptr
)
1075 pstate
->prev_lexptr
= pstate
->lexptr
;
1076 if (pstate
->lexptr
[0] == '\0')
1078 if (pstate
->parse_completion
)
1080 current_string_val
.length
=0;
1081 current_string_val
.ptr
= "";
1087 if (pstate
->lexptr
[0] >= '0' && pstate
->lexptr
[0] <= '9')
1088 return lex_number ();
1089 else if (pstate
->lexptr
[0] == 'b' && pstate
->lexptr
[1] == '\'')
1090 return lex_character ();
1091 else if (pstate
->lexptr
[0] == 'b' && pstate
->lexptr
[1] == '"')
1092 return lex_string ();
1093 else if (pstate
->lexptr
[0] == 'b' && starts_raw_string (pstate
->lexptr
+ 1))
1094 return lex_string ();
1095 else if (starts_raw_string (pstate
->lexptr
))
1096 return lex_string ();
1097 else if (rust_identifier_start_p (pstate
->lexptr
[0]))
1098 return lex_identifier ();
1099 else if (pstate
->lexptr
[0] == '"')
1100 return lex_string ();
1101 else if (pstate
->lexptr
[0] == '\'')
1102 return lex_character ();
1103 else if (pstate
->lexptr
[0] == '}' || pstate
->lexptr
[0] == ']')
1105 /* Falls through to lex_operator. */
1108 else if (pstate
->lexptr
[0] == '(' || pstate
->lexptr
[0] == '{')
1110 /* Falls through to lex_operator. */
1113 else if (pstate
->lexptr
[0] == ',' && pstate
->comma_terminates
1114 && paren_depth
== 0)
1117 return lex_operator ();
1120 /* Push back a single character to be re-lexed. */
1123 rust_parser::push_back (char c
)
1125 /* Can't be called before any lexing. */
1126 gdb_assert (pstate
->prev_lexptr
!= NULL
);
1129 gdb_assert (*pstate
->lexptr
== c
);
1134 /* Parse a tuple or paren expression. */
1137 rust_parser::parse_tuple ()
1141 if (current_token
== ')')
1144 struct type
*unit
= get_type ("()");
1145 return make_operation
<long_const_operation
> (unit
, 0);
1148 operation_up expr
= parse_expr ();
1149 if (current_token
== ')')
1151 /* Parenthesized expression. */
1153 return make_operation
<rust_parenthesized_operation
> (std::move (expr
));
1156 std::vector
<operation_up
> ops
;
1157 ops
.push_back (std::move (expr
));
1158 while (current_token
!= ')')
1160 if (current_token
!= ',')
1161 error (_("',' or ')' expected"));
1164 /* A trailing "," is ok. */
1165 if (current_token
!= ')')
1166 ops
.push_back (parse_expr ());
1171 error (_("Tuple expressions not supported yet"));
1174 /* Parse an array expression. */
1177 rust_parser::parse_array ()
1181 if (current_token
== KW_MUT
)
1184 operation_up result
;
1185 operation_up expr
= parse_expr ();
1186 if (current_token
== ';')
1189 operation_up rhs
= parse_expr ();
1190 result
= make_operation
<rust_array_operation
> (std::move (expr
),
1193 else if (current_token
== ',' || current_token
== ']')
1195 std::vector
<operation_up
> ops
;
1196 ops
.push_back (std::move (expr
));
1197 while (current_token
!= ']')
1199 if (current_token
!= ',')
1200 error (_("',' or ']' expected"));
1202 ops
.push_back (parse_expr ());
1204 ops
.shrink_to_fit ();
1205 int len
= ops
.size () - 1;
1206 result
= make_operation
<array_operation
> (0, len
, std::move (ops
));
1209 error (_("',', ';', or ']' expected"));
1216 /* Turn a name into an operation. */
1219 rust_parser::name_to_operation (const std::string
&name
)
1221 struct block_symbol sym
= lookup_symbol (name
.c_str (),
1222 pstate
->expression_context_block
,
1224 if (sym
.symbol
!= nullptr && sym
.symbol
->aclass () != LOC_TYPEDEF
)
1225 return make_operation
<var_value_operation
> (sym
);
1227 struct type
*type
= nullptr;
1229 if (sym
.symbol
!= nullptr)
1231 gdb_assert (sym
.symbol
->aclass () == LOC_TYPEDEF
);
1232 type
= sym
.symbol
->type ();
1234 if (type
== nullptr)
1235 type
= rust_lookup_type (name
.c_str ());
1236 if (type
== nullptr)
1237 error (_("No symbol '%s' in current context"), name
.c_str ());
1239 if (type
->code () == TYPE_CODE_STRUCT
&& type
->num_fields () == 0)
1241 /* A unit-like struct. */
1242 operation_up
result (new rust_aggregate_operation (type
, {}, {}));
1246 return make_operation
<type_operation
> (type
);
1249 /* Parse a struct expression. */
1252 rust_parser::parse_struct_expr (struct type
*type
)
1256 if (type
->code () != TYPE_CODE_STRUCT
1257 || rust_tuple_type_p (type
)
1258 || rust_tuple_struct_type_p (type
))
1259 error (_("Struct expression applied to non-struct type"));
1261 std::vector
<std::pair
<std::string
, operation_up
>> field_v
;
1262 while (current_token
!= '}' && current_token
!= DOTDOT
)
1264 if (current_token
!= IDENT
)
1265 error (_("'}', '..', or identifier expected"));
1267 std::string name
= get_string ();
1271 if (current_token
== ',' || current_token
== '}'
1272 || current_token
== DOTDOT
)
1273 expr
= name_to_operation (name
);
1277 expr
= parse_expr ();
1279 field_v
.emplace_back (std::move (name
), std::move (expr
));
1281 /* A trailing "," is ok. */
1282 if (current_token
== ',')
1286 operation_up others
;
1287 if (current_token
== DOTDOT
)
1290 others
= parse_expr ();
1295 return make_operation
<rust_aggregate_operation
> (type
,
1297 std::move (field_v
));
1300 /* Used by the operator precedence parser. */
1303 rustop_item (int token_
, int precedence_
, enum exp_opcode opcode_
,
1306 precedence (precedence_
),
1308 op (std::move (op_
))
1312 /* The token value. */
1314 /* Precedence of this operator. */
1316 /* This is used only for assign-modify. */
1317 enum exp_opcode opcode
;
1318 /* The right hand side of this operation. */
1322 /* An operator precedence parser for binary operations, including
1326 rust_parser::parse_binop (bool required
)
1328 /* All the binary operators. Each one is of the form
1329 OPERATION(TOKEN, PRECEDENCE, TYPE)
1330 TOKEN is the corresponding operator token.
1331 PRECEDENCE is a value indicating relative precedence.
1332 TYPE is the operation type corresponding to the operator.
1333 Assignment operations are handled specially, not via this
1334 table; they have precedence 0. */
1336 OPERATION ('*', 10, mul_operation) \
1337 OPERATION ('/', 10, div_operation) \
1338 OPERATION ('%', 10, rem_operation) \
1339 OPERATION ('@', 9, repeat_operation) \
1340 OPERATION ('+', 8, add_operation) \
1341 OPERATION ('-', 8, sub_operation) \
1342 OPERATION (LSH, 7, lsh_operation) \
1343 OPERATION (RSH, 7, rsh_operation) \
1344 OPERATION ('&', 6, bitwise_and_operation) \
1345 OPERATION ('^', 5, bitwise_xor_operation) \
1346 OPERATION ('|', 4, bitwise_ior_operation) \
1347 OPERATION (EQEQ, 3, equal_operation) \
1348 OPERATION (NOTEQ, 3, notequal_operation) \
1349 OPERATION ('<', 3, less_operation) \
1350 OPERATION (LTEQ, 3, leq_operation) \
1351 OPERATION ('>', 3, gtr_operation) \
1352 OPERATION (GTEQ, 3, geq_operation) \
1353 OPERATION (ANDAND, 2, logical_and_operation) \
1354 OPERATION (OROR, 1, logical_or_operation)
1356 #define ASSIGN_PREC 0
1358 operation_up start
= parse_atom (required
);
1359 if (start
== nullptr)
1361 gdb_assert (!required
);
1365 std::vector
<rustop_item
> operator_stack
;
1366 operator_stack
.emplace_back (0, -1, OP_NULL
, std::move (start
));
1370 int this_token
= current_token
;
1371 enum exp_opcode compound_assign_op
= OP_NULL
;
1372 int precedence
= -2;
1376 #define OPERATION(TOKEN, PRECEDENCE, TYPE) \
1378 precedence = PRECEDENCE; \
1386 case COMPOUND_ASSIGN
:
1387 compound_assign_op
= current_opcode
;
1390 precedence
= ASSIGN_PREC
;
1394 /* "as" must be handled specially. */
1398 rustop_item
&lhs
= operator_stack
.back ();
1399 struct type
*type
= parse_type ();
1400 lhs
.op
= make_operation
<unop_cast_operation
> (std::move (lhs
.op
),
1403 /* Bypass the rest of the loop. */
1407 /* Arrange to pop the entire stack. */
1412 /* Make sure that assignments are right-associative while other
1413 operations are left-associative. */
1414 while ((precedence
== ASSIGN_PREC
1415 ? precedence
< operator_stack
.back ().precedence
1416 : precedence
<= operator_stack
.back ().precedence
)
1417 && operator_stack
.size () > 1)
1419 rustop_item rhs
= std::move (operator_stack
.back ());
1420 operator_stack
.pop_back ();
1422 rustop_item
&lhs
= operator_stack
.back ();
1426 #define OPERATION(TOKEN, PRECEDENCE, TYPE) \
1428 lhs.op = make_operation<TYPE> (std::move (lhs.op), \
1429 std::move (rhs.op)); \
1437 case COMPOUND_ASSIGN
:
1439 if (rhs
.token
== '=')
1440 lhs
.op
= (make_operation
<assign_operation
>
1441 (std::move (lhs
.op
), std::move (rhs
.op
)));
1443 lhs
.op
= (make_operation
<assign_modify_operation
>
1444 (rhs
.opcode
, std::move (lhs
.op
),
1445 std::move (rhs
.op
)));
1447 struct type
*unit_type
= get_type ("()");
1449 operation_up
nil (new long_const_operation (unit_type
, 0));
1450 lhs
.op
= (make_operation
<comma_operation
>
1451 (std::move (lhs
.op
), std::move (nil
)));
1456 gdb_assert_not_reached ("bad binary operator");
1460 if (precedence
== -2)
1463 operator_stack
.emplace_back (this_token
, precedence
, compound_assign_op
,
1467 gdb_assert (operator_stack
.size () == 1);
1468 return std::move (operator_stack
[0].op
);
1472 /* Parse a range expression. */
1475 rust_parser::parse_range ()
1477 enum range_flag kind
= (RANGE_HIGH_BOUND_DEFAULT
1478 | RANGE_LOW_BOUND_DEFAULT
);
1481 if (current_token
!= DOTDOT
&& current_token
!= DOTDOTEQ
)
1483 lhs
= parse_binop (true);
1484 kind
&= ~RANGE_LOW_BOUND_DEFAULT
;
1487 if (current_token
== DOTDOT
)
1488 kind
|= RANGE_HIGH_BOUND_EXCLUSIVE
;
1489 else if (current_token
!= DOTDOTEQ
)
1493 /* A "..=" range requires a high bound, but otherwise it is
1495 operation_up rhs
= parse_binop ((kind
& RANGE_HIGH_BOUND_EXCLUSIVE
) == 0);
1497 kind
&= ~RANGE_HIGH_BOUND_DEFAULT
;
1499 return make_operation
<rust_range_operation
> (kind
,
1504 /* Parse an expression. */
1507 rust_parser::parse_expr ()
1509 return parse_range ();
1512 /* Parse a sizeof expression. */
1515 rust_parser::parse_sizeof ()
1520 operation_up result
= make_operation
<unop_sizeof_operation
> (parse_expr ());
1525 /* Parse an address-of operation. */
1528 rust_parser::parse_addr ()
1532 if (current_token
== KW_MUT
)
1535 return make_operation
<rust_unop_addr_operation
> (parse_atom (true));
1538 /* Parse a field expression. */
1541 rust_parser::parse_field (operation_up
&&lhs
)
1545 operation_up result
;
1546 switch (current_token
)
1551 bool is_complete
= current_token
== COMPLETE
;
1552 auto struct_op
= new rust_structop (std::move (lhs
), get_string ());
1556 completion_op
.reset (struct_op
);
1557 pstate
->mark_struct_expression (struct_op
);
1558 /* Throw to the outermost level of the parser. */
1559 error (_("not really an error"));
1561 result
.reset (struct_op
);
1565 case DECIMAL_INTEGER
:
1567 int idx
= current_int_val
.val
.as_integer
<int> ();
1568 result
= make_operation
<rust_struct_anon
> (idx
, std::move (lhs
));
1574 error (_("'_' not allowed in integers in anonymous field references"));
1577 error (_("field name expected"));
1583 /* Parse an index expression. */
1586 rust_parser::parse_index (operation_up
&&lhs
)
1589 operation_up rhs
= parse_expr ();
1592 return make_operation
<rust_subscript_operation
> (std::move (lhs
),
1596 /* Parse a sequence of comma-separated expressions in parens. */
1598 std::vector
<operation_up
>
1599 rust_parser::parse_paren_args ()
1603 std::vector
<operation_up
> args
;
1604 while (current_token
!= ')')
1608 if (current_token
!= ',')
1609 error (_("',' or ')' expected"));
1613 args
.push_back (parse_expr ());
1621 /* Parse the parenthesized part of a function call. */
1624 rust_parser::parse_call (operation_up
&&lhs
)
1626 std::vector
<operation_up
> args
= parse_paren_args ();
1628 return make_operation
<funcall_operation
> (std::move (lhs
),
1632 /* Parse a list of types. */
1634 std::vector
<struct type
*>
1635 rust_parser::parse_type_list ()
1637 std::vector
<struct type
*> result
;
1638 result
.push_back (parse_type ());
1639 while (current_token
== ',')
1642 result
.push_back (parse_type ());
1647 /* Parse a possibly-empty list of types, surrounded in parens. */
1649 std::vector
<struct type
*>
1650 rust_parser::parse_maybe_type_list ()
1653 std::vector
<struct type
*> types
;
1654 if (current_token
!= ')')
1655 types
= parse_type_list ();
1660 /* Parse an array type. */
1663 rust_parser::parse_array_type ()
1666 struct type
*elt_type
= parse_type ();
1669 if (current_token
!= INTEGER
&& current_token
!= DECIMAL_INTEGER
)
1670 error (_("integer expected"));
1671 ULONGEST val
= current_int_val
.val
.as_integer
<ULONGEST
> ();
1675 return lookup_array_range_type (elt_type
, 0, val
- 1);
1678 /* Parse a slice type. */
1681 rust_parser::parse_slice_type ()
1685 /* Handle &str specially. This is an important type in Rust. While
1686 the compiler does emit the "&str" type in the DWARF, just "str"
1687 itself isn't always available -- but it's handy if this works
1689 if (current_token
== IDENT
&& get_string () == "str")
1692 return rust_slice_type ("&str", get_type ("u8"), get_type ("usize"));
1695 bool is_slice
= current_token
== '[';
1699 struct type
*target
= parse_type ();
1704 return rust_slice_type ("&[*gdb*]", target
, get_type ("usize"));
1707 /* For now we treat &x and *x identically. */
1708 return lookup_pointer_type (target
);
1711 /* Parse a pointer type. */
1714 rust_parser::parse_pointer_type ()
1718 if (current_token
== KW_MUT
|| current_token
== KW_CONST
)
1721 struct type
*target
= parse_type ();
1722 /* For the time being we ignore mut/const. */
1723 return lookup_pointer_type (target
);
1726 /* Parse a function type. */
1729 rust_parser::parse_function_type ()
1733 if (current_token
!= '(')
1734 error (_("'(' expected"));
1736 std::vector
<struct type
*> types
= parse_maybe_type_list ();
1738 if (current_token
!= ARROW
)
1739 error (_("'->' expected"));
1742 struct type
*result_type
= parse_type ();
1744 struct type
**argtypes
= nullptr;
1745 if (!types
.empty ())
1746 argtypes
= types
.data ();
1748 result_type
= lookup_function_type_with_arguments (result_type
,
1751 return lookup_pointer_type (result_type
);
1754 /* Parse a tuple type. */
1757 rust_parser::parse_tuple_type ()
1759 std::vector
<struct type
*> types
= parse_maybe_type_list ();
1761 auto_obstack obstack
;
1762 obstack_1grow (&obstack
, '(');
1763 for (int i
= 0; i
< types
.size (); ++i
)
1765 std::string type_name
= type_to_string (types
[i
]);
1768 obstack_1grow (&obstack
, ',');
1769 obstack_grow_str (&obstack
, type_name
.c_str ());
1772 obstack_grow_str0 (&obstack
, ")");
1773 const char *name
= (const char *) obstack_finish (&obstack
);
1775 /* We don't allow creating new tuple types (yet), but we do allow
1776 looking up existing tuple types. */
1777 struct type
*result
= rust_lookup_type (name
);
1778 if (result
== nullptr)
1779 error (_("could not find tuple type '%s'"), name
);
1787 rust_parser::parse_type ()
1789 switch (current_token
)
1792 return parse_array_type ();
1794 return parse_slice_type ();
1796 return parse_pointer_type ();
1798 return parse_function_type ();
1800 return parse_tuple_type ();
1807 std::string path
= parse_path (false);
1808 struct type
*result
= rust_lookup_type (path
.c_str ());
1809 if (result
== nullptr)
1810 error (_("No type name '%s' in current context"), path
.c_str ());
1814 error (_("type expected"));
1821 rust_parser::parse_path (bool for_expr
)
1823 unsigned n_supers
= 0;
1824 int first_token
= current_token
;
1826 switch (current_token
)
1830 if (current_token
!= COLONCOLON
)
1835 while (current_token
== KW_SUPER
)
1839 if (current_token
!= COLONCOLON
)
1840 error (_("'::' expected"));
1850 /* This is a gdb extension to make it possible to refer to items
1851 in other crates. It just bypasses adding the current crate
1852 to the front of the name. */
1857 if (current_token
!= IDENT
)
1858 error (_("identifier expected"));
1859 std::string path
= get_string ();
1860 bool saw_ident
= true;
1863 /* The condition here lets us enter the loop even if we see
1865 while (current_token
== COLONCOLON
|| current_token
== '<')
1867 if (current_token
== COLONCOLON
)
1872 if (current_token
== IDENT
)
1874 path
= path
+ "::" + get_string ();
1878 else if (current_token
== COLONCOLON
)
1880 /* The code below won't detect this scenario. */
1881 error (_("unexpected '::'"));
1885 if (current_token
!= '<')
1888 /* Expression use name::<...>, whereas types use name<...>. */
1891 /* Expressions use "name::<...>", so if we saw an identifier
1892 after the "::", we ignore the "<" here. */
1898 /* Types use "name<...>", so we need to have seen the
1905 std::vector
<struct type
*> types
= parse_type_list ();
1906 if (current_token
== '>')
1908 else if (current_token
== RSH
)
1914 error (_("'>' expected"));
1917 for (int i
= 0; i
< types
.size (); ++i
)
1921 path
+= type_to_string (types
[i
]);
1927 switch (first_token
)
1931 return super_name (path
, n_supers
);
1934 return crate_name (path
);
1943 gdb_assert_not_reached ("missing case in path parsing");
1947 /* Handle the parsing for a string expression. */
1950 rust_parser::parse_string ()
1952 gdb_assert (current_token
== STRING
);
1954 /* Wrap the raw string in the &str struct. */
1955 struct type
*type
= rust_lookup_type ("&str");
1956 if (type
== nullptr)
1957 error (_("Could not find type '&str'"));
1959 std::vector
<std::pair
<std::string
, operation_up
>> field_v
;
1961 size_t len
= current_string_val
.length
;
1962 operation_up str
= make_operation
<string_operation
> (get_string ());
1964 = make_operation
<rust_unop_addr_operation
> (std::move (str
));
1965 field_v
.emplace_back ("data_ptr", std::move (addr
));
1967 struct type
*valtype
= get_type ("usize");
1968 operation_up lenop
= make_operation
<long_const_operation
> (valtype
, len
);
1969 field_v
.emplace_back ("length", std::move (lenop
));
1971 return make_operation
<rust_aggregate_operation
> (type
,
1973 std::move (field_v
));
1976 /* Parse a tuple struct expression. */
1979 rust_parser::parse_tuple_struct (struct type
*type
)
1981 std::vector
<operation_up
> args
= parse_paren_args ();
1983 std::vector
<std::pair
<std::string
, operation_up
>> field_v (args
.size ());
1984 for (int i
= 0; i
< args
.size (); ++i
)
1985 field_v
[i
] = { string_printf ("__%d", i
), std::move (args
[i
]) };
1987 return (make_operation
<rust_aggregate_operation
>
1988 (type
, operation_up (), std::move (field_v
)));
1991 /* Parse a path expression. */
1994 rust_parser::parse_path_expr ()
1996 std::string path
= parse_path (true);
1998 if (current_token
== '{')
2000 struct type
*type
= rust_lookup_type (path
.c_str ());
2001 if (type
== nullptr)
2002 error (_("Could not find type '%s'"), path
.c_str ());
2004 return parse_struct_expr (type
);
2006 else if (current_token
== '(')
2008 struct type
*type
= rust_lookup_type (path
.c_str ());
2009 /* If this is actually a tuple struct expression, handle it
2010 here. If it is a call, it will be handled elsewhere. */
2011 if (type
!= nullptr)
2013 if (!rust_tuple_struct_type_p (type
))
2014 error (_("Type %s is not a tuple struct"), path
.c_str ());
2015 return parse_tuple_struct (type
);
2019 return name_to_operation (path
);
2022 /* Parse an atom. "Atom" isn't a Rust term, but this refers to a
2023 single unitary item in the grammar; but here including some unary
2024 prefix and postfix expressions. */
2027 rust_parser::parse_atom (bool required
)
2029 operation_up result
;
2031 switch (current_token
)
2034 result
= parse_tuple ();
2038 result
= parse_array ();
2042 case DECIMAL_INTEGER
:
2043 result
= make_operation
<long_const_operation
> (current_int_val
.type
,
2044 current_int_val
.val
);
2049 result
= make_operation
<float_const_operation
> (current_float_val
.type
,
2050 current_float_val
.val
);
2055 result
= parse_string ();
2060 result
= make_operation
<string_operation
> (get_string ());
2066 result
= make_operation
<bool_operation
> (current_token
== KW_TRUE
);
2071 /* This is kind of a hacky approach. */
2073 pstate
->push_dollar (current_string_val
);
2074 result
= pstate
->pop ();
2084 result
= parse_path_expr ();
2089 result
= make_operation
<rust_unop_ind_operation
> (parse_atom (true));
2093 result
= make_operation
<unary_plus_operation
> (parse_atom (true));
2097 result
= make_operation
<unary_neg_operation
> (parse_atom (true));
2101 result
= make_operation
<rust_unop_compl_operation
> (parse_atom (true));
2104 result
= parse_sizeof ();
2107 result
= parse_addr ();
2113 error (_("unexpected token"));
2116 /* Now parse suffixes. */
2119 switch (current_token
)
2122 result
= parse_field (std::move (result
));
2126 result
= parse_index (std::move (result
));
2130 result
= parse_call (std::move (result
));
2141 /* The parser as exposed to gdb. */
2144 rust_language::parser (struct parser_state
*state
) const
2146 rust_parser
parser (state
);
2148 operation_up result
;
2151 result
= parser
.parse_entry_point ();
2153 catch (const gdb_exception
&exc
)
2155 if (state
->parse_completion
)
2157 result
= std::move (parser
.completion_op
);
2158 if (result
== nullptr)
2165 state
->set_operation (std::move (result
));
2174 /* A test helper that lexes a string, expecting a single token. */
2177 rust_lex_test_one (rust_parser
*parser
, const char *input
, int expected
)
2181 parser
->reset (input
);
2183 token
= parser
->lex_one_token ();
2184 SELF_CHECK (token
== expected
);
2188 token
= parser
->lex_one_token ();
2189 SELF_CHECK (token
== 0);
2193 /* Test that INPUT lexes as the integer VALUE. */
2196 rust_lex_int_test (rust_parser
*parser
, const char *input
,
2197 ULONGEST value
, int kind
)
2199 rust_lex_test_one (parser
, input
, kind
);
2200 SELF_CHECK (parser
->current_int_val
.val
== value
);
2203 /* Test that INPUT throws an exception with text ERR. */
2206 rust_lex_exception_test (rust_parser
*parser
, const char *input
,
2211 /* The "kind" doesn't matter. */
2212 rust_lex_test_one (parser
, input
, DECIMAL_INTEGER
);
2215 catch (const gdb_exception_error
&except
)
2217 SELF_CHECK (strcmp (except
.what (), err
) == 0);
2221 /* Test that INPUT lexes as the identifier, string, or byte-string
2222 VALUE. KIND holds the expected token kind. */
2225 rust_lex_stringish_test (rust_parser
*parser
, const char *input
,
2226 const char *value
, int kind
)
2228 rust_lex_test_one (parser
, input
, kind
);
2229 SELF_CHECK (parser
->get_string () == value
);
2232 /* Helper to test that a string parses as a given token sequence. */
2235 rust_lex_test_sequence (rust_parser
*parser
, const char *input
, int len
,
2236 const int expected
[])
2240 parser
->reset (input
);
2242 for (i
= 0; i
< len
; ++i
)
2244 int token
= parser
->lex_one_token ();
2245 SELF_CHECK (token
== expected
[i
]);
2249 /* Tests for an integer-parsing corner case. */
2252 rust_lex_test_trailing_dot (rust_parser
*parser
)
2254 const int expected1
[] = { DECIMAL_INTEGER
, '.', IDENT
, '(', ')', 0 };
2255 const int expected2
[] = { INTEGER
, '.', IDENT
, '(', ')', 0 };
2256 const int expected3
[] = { FLOAT
, EQEQ
, '(', ')', 0 };
2257 const int expected4
[] = { DECIMAL_INTEGER
, DOTDOT
, DECIMAL_INTEGER
, 0 };
2259 rust_lex_test_sequence (parser
, "23.g()", ARRAY_SIZE (expected1
), expected1
);
2260 rust_lex_test_sequence (parser
, "23_0.g()", ARRAY_SIZE (expected2
),
2262 rust_lex_test_sequence (parser
, "23.==()", ARRAY_SIZE (expected3
),
2264 rust_lex_test_sequence (parser
, "23..25", ARRAY_SIZE (expected4
), expected4
);
2267 /* Tests of completion. */
2270 rust_lex_test_completion (rust_parser
*parser
)
2272 const int expected
[] = { IDENT
, '.', COMPLETE
, 0 };
2274 parser
->pstate
->parse_completion
= 1;
2276 rust_lex_test_sequence (parser
, "something.wha", ARRAY_SIZE (expected
),
2278 rust_lex_test_sequence (parser
, "something.", ARRAY_SIZE (expected
),
2281 parser
->pstate
->parse_completion
= 0;
2284 /* Test pushback. */
2287 rust_lex_test_push_back (rust_parser
*parser
)
2291 parser
->reset (">>=");
2293 token
= parser
->lex_one_token ();
2294 SELF_CHECK (token
== COMPOUND_ASSIGN
);
2295 SELF_CHECK (parser
->current_opcode
== BINOP_RSH
);
2297 parser
->push_back ('=');
2299 token
= parser
->lex_one_token ();
2300 SELF_CHECK (token
== '=');
2302 token
= parser
->lex_one_token ();
2303 SELF_CHECK (token
== 0);
2306 /* Unit test the lexer. */
2309 rust_lex_tests (void)
2311 /* Set up dummy "parser", so that rust_type works. */
2312 parser_state
ps (language_def (language_rust
), current_inferior ()->arch (),
2313 nullptr, 0, 0, nullptr, 0, nullptr);
2314 rust_parser
parser (&ps
);
2316 rust_lex_test_one (&parser
, "", 0);
2317 rust_lex_test_one (&parser
, " \t \n \r ", 0);
2318 rust_lex_test_one (&parser
, "thread 23", 0);
2319 rust_lex_test_one (&parser
, "task 23", 0);
2320 rust_lex_test_one (&parser
, "th 104", 0);
2321 rust_lex_test_one (&parser
, "ta 97", 0);
2323 rust_lex_int_test (&parser
, "'z'", 'z', INTEGER
);
2324 rust_lex_int_test (&parser
, "'\\xff'", 0xff, INTEGER
);
2325 rust_lex_int_test (&parser
, "'\\u{1016f}'", 0x1016f, INTEGER
);
2326 rust_lex_int_test (&parser
, "b'z'", 'z', INTEGER
);
2327 rust_lex_int_test (&parser
, "b'\\xfe'", 0xfe, INTEGER
);
2328 rust_lex_int_test (&parser
, "b'\\xFE'", 0xfe, INTEGER
);
2329 rust_lex_int_test (&parser
, "b'\\xfE'", 0xfe, INTEGER
);
2331 /* Test all escapes in both modes. */
2332 rust_lex_int_test (&parser
, "'\\n'", '\n', INTEGER
);
2333 rust_lex_int_test (&parser
, "'\\r'", '\r', INTEGER
);
2334 rust_lex_int_test (&parser
, "'\\t'", '\t', INTEGER
);
2335 rust_lex_int_test (&parser
, "'\\\\'", '\\', INTEGER
);
2336 rust_lex_int_test (&parser
, "'\\0'", '\0', INTEGER
);
2337 rust_lex_int_test (&parser
, "'\\''", '\'', INTEGER
);
2338 rust_lex_int_test (&parser
, "'\\\"'", '"', INTEGER
);
2340 rust_lex_int_test (&parser
, "b'\\n'", '\n', INTEGER
);
2341 rust_lex_int_test (&parser
, "b'\\r'", '\r', INTEGER
);
2342 rust_lex_int_test (&parser
, "b'\\t'", '\t', INTEGER
);
2343 rust_lex_int_test (&parser
, "b'\\\\'", '\\', INTEGER
);
2344 rust_lex_int_test (&parser
, "b'\\0'", '\0', INTEGER
);
2345 rust_lex_int_test (&parser
, "b'\\''", '\'', INTEGER
);
2346 rust_lex_int_test (&parser
, "b'\\\"'", '"', INTEGER
);
2348 rust_lex_exception_test (&parser
, "'z", "Unterminated character literal");
2349 rust_lex_exception_test (&parser
, "b'\\x0'", "Not enough hex digits seen");
2350 rust_lex_exception_test (&parser
, "b'\\u{0}'",
2351 "Unicode escape in byte literal");
2352 rust_lex_exception_test (&parser
, "'\\x0'", "Not enough hex digits seen");
2353 rust_lex_exception_test (&parser
, "'\\u0'", "Missing '{' in Unicode escape");
2354 rust_lex_exception_test (&parser
, "'\\u{0", "Missing '}' in Unicode escape");
2355 rust_lex_exception_test (&parser
, "'\\u{0000007}", "Overlong hex escape");
2356 rust_lex_exception_test (&parser
, "'\\u{}", "Not enough hex digits seen");
2357 rust_lex_exception_test (&parser
, "'\\Q'", "Invalid escape \\Q in literal");
2358 rust_lex_exception_test (&parser
, "b'\\Q'", "Invalid escape \\Q in literal");
2360 rust_lex_int_test (&parser
, "23", 23, DECIMAL_INTEGER
);
2361 rust_lex_int_test (&parser
, "2_344__29", 234429, INTEGER
);
2362 rust_lex_int_test (&parser
, "0x1f", 0x1f, INTEGER
);
2363 rust_lex_int_test (&parser
, "23usize", 23, INTEGER
);
2364 rust_lex_int_test (&parser
, "23i32", 23, INTEGER
);
2365 rust_lex_int_test (&parser
, "0x1_f", 0x1f, INTEGER
);
2366 rust_lex_int_test (&parser
, "0b1_101011__", 0x6b, INTEGER
);
2367 rust_lex_int_test (&parser
, "0o001177i64", 639, INTEGER
);
2368 rust_lex_int_test (&parser
, "0x123456789u64", 0x123456789ull
, INTEGER
);
2370 rust_lex_test_trailing_dot (&parser
);
2372 rust_lex_test_one (&parser
, "23.", FLOAT
);
2373 rust_lex_test_one (&parser
, "23.99f32", FLOAT
);
2374 rust_lex_test_one (&parser
, "23e7", FLOAT
);
2375 rust_lex_test_one (&parser
, "23E-7", FLOAT
);
2376 rust_lex_test_one (&parser
, "23e+7", FLOAT
);
2377 rust_lex_test_one (&parser
, "23.99e+7f64", FLOAT
);
2378 rust_lex_test_one (&parser
, "23.82f32", FLOAT
);
2380 rust_lex_stringish_test (&parser
, "hibob", "hibob", IDENT
);
2381 rust_lex_stringish_test (&parser
, "hibob__93", "hibob__93", IDENT
);
2382 rust_lex_stringish_test (&parser
, "thread", "thread", IDENT
);
2383 rust_lex_stringish_test (&parser
, "r#true", "true", IDENT
);
2385 const int expected1
[] = { IDENT
, DECIMAL_INTEGER
, 0 };
2386 rust_lex_test_sequence (&parser
, "r#thread 23", ARRAY_SIZE (expected1
),
2388 const int expected2
[] = { IDENT
, '#', 0 };
2389 rust_lex_test_sequence (&parser
, "r#", ARRAY_SIZE (expected2
), expected2
);
2391 rust_lex_stringish_test (&parser
, "\"string\"", "string", STRING
);
2392 rust_lex_stringish_test (&parser
, "\"str\\ting\"", "str\ting", STRING
);
2393 rust_lex_stringish_test (&parser
, "\"str\\\"ing\"", "str\"ing", STRING
);
2394 rust_lex_stringish_test (&parser
, "r\"str\\ing\"", "str\\ing", STRING
);
2395 rust_lex_stringish_test (&parser
, "r#\"str\\ting\"#", "str\\ting", STRING
);
2396 rust_lex_stringish_test (&parser
, "r###\"str\\\"ing\"###", "str\\\"ing",
2399 rust_lex_stringish_test (&parser
, "b\"string\"", "string", BYTESTRING
);
2400 rust_lex_stringish_test (&parser
, "b\"\x73tring\"", "string", BYTESTRING
);
2401 rust_lex_stringish_test (&parser
, "b\"str\\\"ing\"", "str\"ing", BYTESTRING
);
2402 rust_lex_stringish_test (&parser
, "br####\"\\x73tring\"####", "\\x73tring",
2405 for (const auto &candidate
: identifier_tokens
)
2406 rust_lex_test_one (&parser
, candidate
.name
, candidate
.value
);
2408 for (const auto &candidate
: operator_tokens
)
2409 rust_lex_test_one (&parser
, candidate
.name
, candidate
.value
);
2411 rust_lex_test_completion (&parser
);
2412 rust_lex_test_push_back (&parser
);
2415 #endif /* GDB_SELF_TEST */
2419 void _initialize_rust_exp ();
2421 _initialize_rust_exp ()
2423 int code
= regcomp (&number_regex
, number_regex_text
, REG_EXTENDED
);
2424 /* If the regular expression was incorrect, it was a programming
2426 gdb_assert (code
== 0);
2429 selftests::register_test ("rust-lex", rust_lex_tests
);