1 /* Rust expression parsing for GDB, the GNU debugger.
3 Copyright (C) 2016-2022 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/>. */
24 #include "cp-support.h"
25 #include "gdbsupport/gdb_obstack.h"
26 #include "gdbsupport/gdb_regex.h"
27 #include "rust-lang.h"
28 #include "parser-defs.h"
29 #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))?"
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_enum 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
= block_scope (pstate
->expression_context_block
);
379 if (scope
[0] == '\0')
380 error (_("Couldn't find namespace scope for self::"));
385 std::vector
<int> offsets
;
386 unsigned int current_len
;
388 current_len
= cp_find_first_component (scope
);
389 while (scope
[current_len
] != '\0')
391 offsets
.push_back (current_len
);
392 gdb_assert (scope
[current_len
] == ':');
395 current_len
+= cp_find_first_component (scope
399 len
= offsets
.size ();
401 error (_("Too many super:: uses from '%s'"), scope
);
403 offset
= offsets
[len
- n_supers
];
406 offset
= strlen (scope
);
408 return "::" + std::string (scope
, offset
) + "::" + ident
;
411 /* A helper to appropriately munge NAME and BLOCK depending on the
412 presence of a leading "::". */
415 munge_name_and_block (const char **name
, const struct block
**block
)
417 /* If it is a global reference, skip the current block in favor of
419 if (startswith (*name
, "::"))
422 *block
= block_static_block (*block
);
426 /* Like lookup_symbol, but handles Rust namespace conventions, and
427 doesn't require field_of_this_result. */
430 rust_parser::lookup_symbol (const char *name
, const struct block
*block
,
431 const domain_enum domain
)
433 struct block_symbol result
;
435 munge_name_and_block (&name
, &block
);
437 result
= ::lookup_symbol (name
, block
, domain
, NULL
);
438 if (result
.symbol
!= NULL
)
439 update_innermost_block (result
);
443 /* Look up a type, following Rust namespace conventions. */
446 rust_parser::rust_lookup_type (const char *name
)
448 struct block_symbol result
;
451 const struct block
*block
= pstate
->expression_context_block
;
452 munge_name_and_block (&name
, &block
);
454 result
= ::lookup_symbol (name
, block
, STRUCT_DOMAIN
, NULL
);
455 if (result
.symbol
!= NULL
)
457 update_innermost_block (result
);
458 return result
.symbol
->type ();
461 type
= lookup_typename (language (), name
, NULL
, 1);
465 /* Last chance, try a built-in type. */
466 return language_lookup_primitive_type (language (), arch (), name
);
469 /* A helper that updates the innermost block as appropriate. */
472 rust_parser::update_innermost_block (struct block_symbol sym
)
474 if (symbol_read_needs_frame (sym
.symbol
))
475 pstate
->block_tracker
->update (sym
);
478 /* Lex a hex number with at least MIN digits and at most MAX
482 rust_parser::lex_hex (int min
, int max
)
486 /* We only want to stop at MAX if we're lexing a byte escape. */
487 int check_max
= min
== max
;
489 while ((check_max
? len
<= max
: 1)
490 && ((pstate
->lexptr
[0] >= 'a' && pstate
->lexptr
[0] <= 'f')
491 || (pstate
->lexptr
[0] >= 'A' && pstate
->lexptr
[0] <= 'F')
492 || (pstate
->lexptr
[0] >= '0' && pstate
->lexptr
[0] <= '9')))
495 if (pstate
->lexptr
[0] >= 'a' && pstate
->lexptr
[0] <= 'f')
496 result
= result
+ 10 + pstate
->lexptr
[0] - 'a';
497 else if (pstate
->lexptr
[0] >= 'A' && pstate
->lexptr
[0] <= 'F')
498 result
= result
+ 10 + pstate
->lexptr
[0] - 'A';
500 result
= result
+ pstate
->lexptr
[0] - '0';
506 error (_("Not enough hex digits seen"));
509 gdb_assert (min
!= max
);
510 error (_("Overlong hex escape"));
516 /* Lex an escape. IS_BYTE is true if we're lexing a byte escape;
517 otherwise we're lexing a character escape. */
520 rust_parser::lex_escape (int is_byte
)
524 gdb_assert (pstate
->lexptr
[0] == '\\');
526 switch (pstate
->lexptr
[0])
530 result
= lex_hex (2, 2);
535 error (_("Unicode escape in byte literal"));
537 if (pstate
->lexptr
[0] != '{')
538 error (_("Missing '{' in Unicode escape"));
540 result
= lex_hex (1, 6);
541 /* Could do range checks here. */
542 if (pstate
->lexptr
[0] != '}')
543 error (_("Missing '}' in Unicode escape"));
577 error (_("Invalid escape \\%c in literal"), pstate
->lexptr
[0]);
583 /* A helper for lex_character. Search forward for the closing single
584 quote, then convert the bytes from the host charset to UTF-32. */
587 lex_multibyte_char (const char *text
, int *len
)
589 /* Only look a maximum of 5 bytes for the closing quote. This is
590 the maximum for UTF-8. */
592 gdb_assert (text
[0] != '\'');
593 for (quote
= 1; text
[quote
] != '\0' && text
[quote
] != '\''; ++quote
)
596 /* The caller will issue an error. */
597 if (text
[quote
] == '\0')
601 convert_between_encodings (host_charset (), HOST_UTF32
,
602 (const gdb_byte
*) text
,
603 quote
, 1, &result
, translit_none
);
605 int size
= obstack_object_size (&result
);
607 error (_("overlong character literal"));
609 memcpy (&value
, obstack_finish (&result
), size
);
613 /* Lex a character constant. */
616 rust_parser::lex_character ()
621 if (pstate
->lexptr
[0] == 'b')
626 gdb_assert (pstate
->lexptr
[0] == '\'');
628 if (pstate
->lexptr
[0] == '\'')
629 error (_("empty character literal"));
630 else if (pstate
->lexptr
[0] == '\\')
631 value
= lex_escape (is_byte
);
635 value
= lex_multibyte_char (&pstate
->lexptr
[0], &len
);
636 pstate
->lexptr
+= len
;
639 if (pstate
->lexptr
[0] != '\'')
640 error (_("Unterminated character literal"));
643 current_int_val
.val
= value
;
644 current_int_val
.type
= get_type (is_byte
? "u8" : "char");
649 /* Return the offset of the double quote if STR looks like the start
650 of a raw string, or 0 if STR does not start a raw string. */
653 starts_raw_string (const char *str
)
655 const char *save
= str
;
660 while (str
[0] == '#')
667 /* Return true if STR looks like the end of a raw string that had N
668 hashes at the start. */
671 ends_raw_string (const char *str
, int n
)
675 gdb_assert (str
[0] == '"');
676 for (i
= 0; i
< n
; ++i
)
677 if (str
[i
+ 1] != '#')
682 /* Lex a string constant. */
685 rust_parser::lex_string ()
687 int is_byte
= pstate
->lexptr
[0] == 'b';
692 raw_length
= starts_raw_string (pstate
->lexptr
);
693 pstate
->lexptr
+= raw_length
;
694 gdb_assert (pstate
->lexptr
[0] == '"');
703 if (pstate
->lexptr
[0] == '"' && ends_raw_string (pstate
->lexptr
,
706 /* Exit with lexptr pointing after the final "#". */
707 pstate
->lexptr
+= raw_length
;
710 else if (pstate
->lexptr
[0] == '\0')
711 error (_("Unexpected EOF in string"));
713 value
= pstate
->lexptr
[0] & 0xff;
714 if (is_byte
&& value
> 127)
715 error (_("Non-ASCII value in raw byte string"));
716 obstack_1grow (&obstack
, value
);
720 else if (pstate
->lexptr
[0] == '"')
722 /* Make sure to skip the quote. */
726 else if (pstate
->lexptr
[0] == '\\')
728 value
= lex_escape (is_byte
);
731 obstack_1grow (&obstack
, value
);
733 convert_between_encodings (HOST_UTF32
, "UTF-8",
735 sizeof (value
), sizeof (value
),
736 &obstack
, translit_none
);
738 else if (pstate
->lexptr
[0] == '\0')
739 error (_("Unexpected EOF in string"));
742 value
= pstate
->lexptr
[0] & 0xff;
743 if (is_byte
&& value
> 127)
744 error (_("Non-ASCII value in byte string"));
745 obstack_1grow (&obstack
, value
);
750 current_string_val
.length
= obstack_object_size (&obstack
);
751 current_string_val
.ptr
= (const char *) obstack_finish (&obstack
);
752 return is_byte
? BYTESTRING
: STRING
;
755 /* Return true if STRING starts with whitespace followed by a digit. */
758 space_then_number (const char *string
)
760 const char *p
= string
;
762 while (p
[0] == ' ' || p
[0] == '\t')
767 return *p
>= '0' && *p
<= '9';
770 /* Return true if C can start an identifier. */
773 rust_identifier_start_p (char c
)
775 return ((c
>= 'a' && c
<= 'z')
776 || (c
>= 'A' && c
<= 'Z')
779 /* Allow any non-ASCII character as an identifier. There
780 doesn't seem to be a need to be picky about this. */
784 /* Lex an identifier. */
787 rust_parser::lex_identifier ()
790 const struct token_info
*token
;
791 int is_gdb_var
= pstate
->lexptr
[0] == '$';
794 if (pstate
->lexptr
[0] == 'r'
795 && pstate
->lexptr
[1] == '#'
796 && rust_identifier_start_p (pstate
->lexptr
[2]))
802 const char *start
= pstate
->lexptr
;
803 gdb_assert (rust_identifier_start_p (pstate
->lexptr
[0]));
807 /* Allow any non-ASCII character here. This "handles" UTF-8 by
808 passing it through. */
809 while ((pstate
->lexptr
[0] >= 'a' && pstate
->lexptr
[0] <= 'z')
810 || (pstate
->lexptr
[0] >= 'A' && pstate
->lexptr
[0] <= 'Z')
811 || pstate
->lexptr
[0] == '_'
812 || (is_gdb_var
&& pstate
->lexptr
[0] == '$')
813 || (pstate
->lexptr
[0] >= '0' && pstate
->lexptr
[0] <= '9')
814 || (pstate
->lexptr
[0] & 0x80) != 0)
818 length
= pstate
->lexptr
- start
;
822 for (const auto &candidate
: identifier_tokens
)
824 if (length
== strlen (candidate
.name
)
825 && strncmp (candidate
.name
, start
, length
) == 0)
835 if (token
->value
== 0)
837 /* Leave the terminating token alone. */
838 pstate
->lexptr
= start
;
842 else if (token
== NULL
844 && (strncmp (start
, "thread", length
) == 0
845 || strncmp (start
, "task", length
) == 0)
846 && space_then_number (pstate
->lexptr
))
848 /* "task" or "thread" followed by a number terminates the
849 parse, per gdb rules. */
850 pstate
->lexptr
= start
;
854 if (token
== NULL
|| (pstate
->parse_completion
&& pstate
->lexptr
[0] == '\0'))
856 current_string_val
.length
= length
;
857 current_string_val
.ptr
= start
;
860 if (pstate
->parse_completion
&& pstate
->lexptr
[0] == '\0')
862 /* Prevent rustyylex from returning two COMPLETE tokens. */
863 pstate
->prev_lexptr
= pstate
->lexptr
;
874 /* Lex an operator. */
877 rust_parser::lex_operator ()
879 const struct token_info
*token
= NULL
;
881 for (const auto &candidate
: operator_tokens
)
883 if (strncmp (candidate
.name
, pstate
->lexptr
,
884 strlen (candidate
.name
)) == 0)
886 pstate
->lexptr
+= strlen (candidate
.name
);
894 current_opcode
= token
->opcode
;
898 return *pstate
->lexptr
++;
904 rust_parser::lex_number ()
906 regmatch_t subexps
[NUM_SUBEXPRESSIONS
];
909 int could_be_decimal
= 1;
910 int implicit_i32
= 0;
911 const char *type_name
= NULL
;
917 match
= regexec (&number_regex
, pstate
->lexptr
, ARRAY_SIZE (subexps
),
919 /* Failure means the regexp is broken. */
920 gdb_assert (match
== 0);
922 if (subexps
[INT_TEXT
].rm_so
!= -1)
924 /* Integer part matched. */
926 end_index
= subexps
[INT_TEXT
].rm_eo
;
927 if (subexps
[INT_TYPE
].rm_so
== -1)
934 type_index
= INT_TYPE
;
935 could_be_decimal
= 0;
938 else if (subexps
[FLOAT_TYPE1
].rm_so
!= -1)
940 /* Found floating point type suffix. */
941 end_index
= subexps
[FLOAT_TYPE1
].rm_so
;
942 type_index
= FLOAT_TYPE1
;
944 else if (subexps
[FLOAT_TYPE2
].rm_so
!= -1)
946 /* Found floating point type suffix. */
947 end_index
= subexps
[FLOAT_TYPE2
].rm_so
;
948 type_index
= FLOAT_TYPE2
;
952 /* Any other floating point match. */
953 end_index
= subexps
[0].rm_eo
;
957 /* We need a special case if the final character is ".". In this
958 case we might need to parse an integer. For example, "23.f()" is
959 a request for a trait method call, not a syntax error involving
960 the floating point number "23.". */
961 gdb_assert (subexps
[0].rm_eo
> 0);
962 if (pstate
->lexptr
[subexps
[0].rm_eo
- 1] == '.')
964 const char *next
= skip_spaces (&pstate
->lexptr
[subexps
[0].rm_eo
]);
966 if (rust_identifier_start_p (*next
) || *next
== '.')
970 end_index
= subexps
[0].rm_eo
;
972 could_be_decimal
= 1;
977 /* Compute the type name if we haven't already. */
978 std::string type_name_holder
;
979 if (type_name
== NULL
)
981 gdb_assert (type_index
!= -1);
982 type_name_holder
= std::string ((pstate
->lexptr
983 + subexps
[type_index
].rm_so
),
984 (subexps
[type_index
].rm_eo
985 - subexps
[type_index
].rm_so
));
986 type_name
= type_name_holder
.c_str ();
989 /* Look up the type. */
990 type
= get_type (type_name
);
992 /* Copy the text of the number and remove the "_"s. */
994 for (i
= 0; i
< end_index
&& pstate
->lexptr
[i
]; ++i
)
996 if (pstate
->lexptr
[i
] == '_')
997 could_be_decimal
= 0;
999 number
.push_back (pstate
->lexptr
[i
]);
1002 /* Advance past the match. */
1003 pstate
->lexptr
+= subexps
[0].rm_eo
;
1005 /* Parse the number. */
1012 if (number
[0] == '0')
1014 if (number
[1] == 'x')
1016 else if (number
[1] == 'o')
1018 else if (number
[1] == 'b')
1023 could_be_decimal
= 0;
1027 value
= strtoulst (number
.c_str () + offset
, NULL
, radix
);
1028 if (implicit_i32
&& value
>= ((uint64_t) 1) << 31)
1029 type
= get_type ("i64");
1031 current_int_val
.val
= value
;
1032 current_int_val
.type
= type
;
1036 current_float_val
.type
= type
;
1037 bool parsed
= parse_float (number
.c_str (), number
.length (),
1038 current_float_val
.type
,
1039 current_float_val
.val
.data ());
1040 gdb_assert (parsed
);
1043 return is_integer
? (could_be_decimal
? DECIMAL_INTEGER
: INTEGER
) : FLOAT
;
1049 rust_parser::lex_one_token ()
1051 /* Skip all leading whitespace. */
1052 while (pstate
->lexptr
[0] == ' '
1053 || pstate
->lexptr
[0] == '\t'
1054 || pstate
->lexptr
[0] == '\r'
1055 || pstate
->lexptr
[0] == '\n')
1058 /* If we hit EOF and we're completing, then return COMPLETE -- maybe
1059 we're completing an empty string at the end of a field_expr.
1060 But, we don't want to return two COMPLETE tokens in a row. */
1061 if (pstate
->lexptr
[0] == '\0' && pstate
->lexptr
== pstate
->prev_lexptr
)
1063 pstate
->prev_lexptr
= pstate
->lexptr
;
1064 if (pstate
->lexptr
[0] == '\0')
1066 if (pstate
->parse_completion
)
1068 current_string_val
.length
=0;
1069 current_string_val
.ptr
= "";
1075 if (pstate
->lexptr
[0] >= '0' && pstate
->lexptr
[0] <= '9')
1076 return lex_number ();
1077 else if (pstate
->lexptr
[0] == 'b' && pstate
->lexptr
[1] == '\'')
1078 return lex_character ();
1079 else if (pstate
->lexptr
[0] == 'b' && pstate
->lexptr
[1] == '"')
1080 return lex_string ();
1081 else if (pstate
->lexptr
[0] == 'b' && starts_raw_string (pstate
->lexptr
+ 1))
1082 return lex_string ();
1083 else if (starts_raw_string (pstate
->lexptr
))
1084 return lex_string ();
1085 else if (rust_identifier_start_p (pstate
->lexptr
[0]))
1086 return lex_identifier ();
1087 else if (pstate
->lexptr
[0] == '"')
1088 return lex_string ();
1089 else if (pstate
->lexptr
[0] == '\'')
1090 return lex_character ();
1091 else if (pstate
->lexptr
[0] == '}' || pstate
->lexptr
[0] == ']')
1093 /* Falls through to lex_operator. */
1096 else if (pstate
->lexptr
[0] == '(' || pstate
->lexptr
[0] == '{')
1098 /* Falls through to lex_operator. */
1101 else if (pstate
->lexptr
[0] == ',' && pstate
->comma_terminates
1102 && paren_depth
== 0)
1105 return lex_operator ();
1108 /* Push back a single character to be re-lexed. */
1111 rust_parser::push_back (char c
)
1113 /* Can't be called before any lexing. */
1114 gdb_assert (pstate
->prev_lexptr
!= NULL
);
1117 gdb_assert (*pstate
->lexptr
== c
);
1122 /* Parse a tuple or paren expression. */
1125 rust_parser::parse_tuple ()
1129 if (current_token
== ')')
1132 struct type
*unit
= get_type ("()");
1133 return make_operation
<long_const_operation
> (unit
, 0);
1136 operation_up expr
= parse_expr ();
1137 if (current_token
== ')')
1139 /* Parenthesized expression. */
1141 return make_operation
<rust_parenthesized_operation
> (std::move (expr
));
1144 std::vector
<operation_up
> ops
;
1145 ops
.push_back (std::move (expr
));
1146 while (current_token
!= ')')
1148 if (current_token
!= ',')
1149 error (_("',' or ')' expected"));
1152 /* A trailing "," is ok. */
1153 if (current_token
!= ')')
1154 ops
.push_back (parse_expr ());
1159 error (_("Tuple expressions not supported yet"));
1162 /* Parse an array expression. */
1165 rust_parser::parse_array ()
1169 if (current_token
== KW_MUT
)
1172 operation_up result
;
1173 operation_up expr
= parse_expr ();
1174 if (current_token
== ';')
1177 operation_up rhs
= parse_expr ();
1178 result
= make_operation
<rust_array_operation
> (std::move (expr
),
1181 else if (current_token
== ',')
1183 std::vector
<operation_up
> ops
;
1184 ops
.push_back (std::move (expr
));
1185 while (current_token
!= ']')
1187 if (current_token
!= ',')
1188 error (_("',' or ']' expected"));
1190 ops
.push_back (parse_expr ());
1192 ops
.shrink_to_fit ();
1193 int len
= ops
.size () - 1;
1194 result
= make_operation
<array_operation
> (0, len
, std::move (ops
));
1196 else if (current_token
!= ']')
1197 error (_("',', ';', or ']' expected"));
1204 /* Turn a name into an operation. */
1207 rust_parser::name_to_operation (const std::string
&name
)
1209 struct block_symbol sym
= lookup_symbol (name
.c_str (),
1210 pstate
->expression_context_block
,
1212 if (sym
.symbol
!= nullptr && sym
.symbol
->aclass () != LOC_TYPEDEF
)
1213 return make_operation
<var_value_operation
> (sym
);
1215 struct type
*type
= nullptr;
1217 if (sym
.symbol
!= nullptr)
1219 gdb_assert (sym
.symbol
->aclass () == LOC_TYPEDEF
);
1220 type
= sym
.symbol
->type ();
1222 if (type
== nullptr)
1223 type
= rust_lookup_type (name
.c_str ());
1224 if (type
== nullptr)
1225 error (_("No symbol '%s' in current context"), name
.c_str ());
1227 if (type
->code () == TYPE_CODE_STRUCT
&& type
->num_fields () == 0)
1229 /* A unit-like struct. */
1230 operation_up
result (new rust_aggregate_operation (type
, {}, {}));
1234 return make_operation
<type_operation
> (type
);
1237 /* Parse a struct expression. */
1240 rust_parser::parse_struct_expr (struct type
*type
)
1244 if (type
->code () != TYPE_CODE_STRUCT
1245 || rust_tuple_type_p (type
)
1246 || rust_tuple_struct_type_p (type
))
1247 error (_("Struct expression applied to non-struct type"));
1249 std::vector
<std::pair
<std::string
, operation_up
>> field_v
;
1250 while (current_token
!= '}' && current_token
!= DOTDOT
)
1252 if (current_token
!= IDENT
)
1253 error (_("'}', '..', or identifier expected"));
1255 std::string name
= get_string ();
1259 if (current_token
== ',' || current_token
== '}'
1260 || current_token
== DOTDOT
)
1261 expr
= name_to_operation (name
);
1265 expr
= parse_expr ();
1267 field_v
.emplace_back (std::move (name
), std::move (expr
));
1269 /* A trailing "," is ok. */
1270 if (current_token
== ',')
1274 operation_up others
;
1275 if (current_token
== DOTDOT
)
1278 others
= parse_expr ();
1283 return make_operation
<rust_aggregate_operation
> (type
,
1285 std::move (field_v
));
1288 /* Used by the operator precedence parser. */
1291 rustop_item (int token_
, int precedence_
, enum exp_opcode opcode_
,
1294 precedence (precedence_
),
1296 op (std::move (op_
))
1300 /* The token value. */
1302 /* Precedence of this operator. */
1304 /* This is used only for assign-modify. */
1305 enum exp_opcode opcode
;
1306 /* The right hand side of this operation. */
1310 /* An operator precedence parser for binary operations, including
1314 rust_parser::parse_binop (bool required
)
1316 /* All the binary operators. Each one is of the form
1317 OPERATION(TOKEN, PRECEDENCE, TYPE)
1318 TOKEN is the corresponding operator token.
1319 PRECEDENCE is a value indicating relative precedence.
1320 TYPE is the operation type corresponding to the operator.
1321 Assignment operations are handled specially, not via this
1322 table; they have precedence 0. */
1324 OPERATION ('*', 10, mul_operation) \
1325 OPERATION ('/', 10, div_operation) \
1326 OPERATION ('%', 10, rem_operation) \
1327 OPERATION ('@', 9, repeat_operation) \
1328 OPERATION ('+', 8, add_operation) \
1329 OPERATION ('-', 8, sub_operation) \
1330 OPERATION (LSH, 7, lsh_operation) \
1331 OPERATION (RSH, 7, rsh_operation) \
1332 OPERATION ('&', 6, bitwise_and_operation) \
1333 OPERATION ('^', 5, bitwise_xor_operation) \
1334 OPERATION ('|', 4, bitwise_ior_operation) \
1335 OPERATION (EQEQ, 3, equal_operation) \
1336 OPERATION (NOTEQ, 3, notequal_operation) \
1337 OPERATION ('<', 3, less_operation) \
1338 OPERATION (LTEQ, 3, leq_operation) \
1339 OPERATION ('>', 3, gtr_operation) \
1340 OPERATION (GTEQ, 3, geq_operation) \
1341 OPERATION (ANDAND, 2, logical_and_operation) \
1342 OPERATION (OROR, 1, logical_or_operation)
1344 operation_up start
= parse_atom (required
);
1345 if (start
== nullptr)
1347 gdb_assert (!required
);
1351 std::vector
<rustop_item
> operator_stack
;
1352 operator_stack
.emplace_back (0, -1, OP_NULL
, std::move (start
));
1356 int this_token
= current_token
;
1357 enum exp_opcode compound_assign_op
= OP_NULL
;
1358 int precedence
= -2;
1362 #define OPERATION(TOKEN, PRECEDENCE, TYPE) \
1364 precedence = PRECEDENCE; \
1372 case COMPOUND_ASSIGN
:
1373 compound_assign_op
= current_opcode
;
1380 /* "as" must be handled specially. */
1384 rustop_item
&lhs
= operator_stack
.back ();
1385 struct type
*type
= parse_type ();
1386 lhs
.op
= make_operation
<unop_cast_operation
> (std::move (lhs
.op
),
1389 /* Bypass the rest of the loop. */
1393 /* Arrange to pop the entire stack. */
1398 while (precedence
< operator_stack
.back ().precedence
1399 && operator_stack
.size () > 1)
1401 rustop_item rhs
= std::move (operator_stack
.back ());
1402 operator_stack
.pop_back ();
1404 rustop_item
&lhs
= operator_stack
.back ();
1408 #define OPERATION(TOKEN, PRECEDENCE, TYPE) \
1410 lhs.op = make_operation<TYPE> (std::move (lhs.op), \
1411 std::move (rhs.op)); \
1419 case COMPOUND_ASSIGN
:
1421 if (rhs
.token
== '=')
1422 lhs
.op
= (make_operation
<assign_operation
>
1423 (std::move (lhs
.op
), std::move (rhs
.op
)));
1425 lhs
.op
= (make_operation
<assign_modify_operation
>
1426 (rhs
.opcode
, std::move (lhs
.op
),
1427 std::move (rhs
.op
)));
1429 struct type
*unit_type
= get_type ("()");
1431 operation_up
nil (new long_const_operation (unit_type
, 0));
1432 lhs
.op
= (make_operation
<comma_operation
>
1433 (std::move (lhs
.op
), std::move (nil
)));
1438 gdb_assert_not_reached ("bad binary operator");
1442 if (precedence
== -2)
1445 operator_stack
.emplace_back (this_token
, precedence
, compound_assign_op
,
1449 gdb_assert (operator_stack
.size () == 1);
1450 return std::move (operator_stack
[0].op
);
1454 /* Parse a range expression. */
1457 rust_parser::parse_range ()
1459 enum range_flag kind
= (RANGE_HIGH_BOUND_DEFAULT
1460 | RANGE_LOW_BOUND_DEFAULT
);
1463 if (current_token
!= DOTDOT
&& current_token
!= DOTDOTEQ
)
1465 lhs
= parse_binop (true);
1466 kind
&= ~RANGE_LOW_BOUND_DEFAULT
;
1469 if (current_token
== DOTDOT
)
1470 kind
|= RANGE_HIGH_BOUND_EXCLUSIVE
;
1471 else if (current_token
!= DOTDOTEQ
)
1475 /* A "..=" range requires a high bound, but otherwise it is
1477 operation_up rhs
= parse_binop ((kind
& RANGE_HIGH_BOUND_EXCLUSIVE
) == 0);
1479 kind
&= ~RANGE_HIGH_BOUND_DEFAULT
;
1481 return make_operation
<rust_range_operation
> (kind
,
1486 /* Parse an expression. */
1489 rust_parser::parse_expr ()
1491 return parse_range ();
1494 /* Parse a sizeof expression. */
1497 rust_parser::parse_sizeof ()
1502 operation_up result
= make_operation
<unop_sizeof_operation
> (parse_expr ());
1507 /* Parse an address-of operation. */
1510 rust_parser::parse_addr ()
1514 if (current_token
== KW_MUT
)
1517 return make_operation
<rust_unop_addr_operation
> (parse_atom (true));
1520 /* Parse a field expression. */
1523 rust_parser::parse_field (operation_up
&&lhs
)
1527 operation_up result
;
1528 switch (current_token
)
1533 bool is_complete
= current_token
== COMPLETE
;
1534 auto struct_op
= new rust_structop (std::move (lhs
), get_string ());
1538 completion_op
.reset (struct_op
);
1539 pstate
->mark_struct_expression (struct_op
);
1540 /* Throw to the outermost level of the parser. */
1541 error (_("not really an error"));
1543 result
.reset (struct_op
);
1547 case DECIMAL_INTEGER
:
1548 result
= make_operation
<rust_struct_anon
> (current_int_val
.val
,
1554 error (_("'_' not allowed in integers in anonymous field references"));
1557 error (_("field name expected"));
1563 /* Parse an index expression. */
1566 rust_parser::parse_index (operation_up
&&lhs
)
1569 operation_up rhs
= parse_expr ();
1572 return make_operation
<rust_subscript_operation
> (std::move (lhs
),
1576 /* Parse a sequence of comma-separated expressions in parens. */
1578 std::vector
<operation_up
>
1579 rust_parser::parse_paren_args ()
1583 std::vector
<operation_up
> args
;
1584 while (current_token
!= ')')
1588 if (current_token
!= ',')
1589 error (_("',' or ')' expected"));
1593 args
.push_back (parse_expr ());
1601 /* Parse the parenthesized part of a function call. */
1604 rust_parser::parse_call (operation_up
&&lhs
)
1606 std::vector
<operation_up
> args
= parse_paren_args ();
1608 return make_operation
<funcall_operation
> (std::move (lhs
),
1612 /* Parse a list of types. */
1614 std::vector
<struct type
*>
1615 rust_parser::parse_type_list ()
1617 std::vector
<struct type
*> result
;
1618 result
.push_back (parse_type ());
1619 while (current_token
== ',')
1622 result
.push_back (parse_type ());
1627 /* Parse a possibly-empty list of types, surrounded in parens. */
1629 std::vector
<struct type
*>
1630 rust_parser::parse_maybe_type_list ()
1633 std::vector
<struct type
*> types
;
1634 if (current_token
!= ')')
1635 types
= parse_type_list ();
1640 /* Parse an array type. */
1643 rust_parser::parse_array_type ()
1646 struct type
*elt_type
= parse_type ();
1649 if (current_token
!= INTEGER
&& current_token
!= DECIMAL_INTEGER
)
1650 error (_("integer expected"));
1651 ULONGEST val
= current_int_val
.val
;
1655 return lookup_array_range_type (elt_type
, 0, val
- 1);
1658 /* Parse a slice type. */
1661 rust_parser::parse_slice_type ()
1665 bool is_slice
= current_token
== '[';
1669 struct type
*target
= parse_type ();
1674 return rust_slice_type ("&[*gdb*]", target
, get_type ("usize"));
1677 /* For now we treat &x and *x identically. */
1678 return lookup_pointer_type (target
);
1681 /* Parse a pointer type. */
1684 rust_parser::parse_pointer_type ()
1688 if (current_token
== KW_MUT
|| current_token
== KW_CONST
)
1691 struct type
*target
= parse_type ();
1692 /* For the time being we ignore mut/const. */
1693 return lookup_pointer_type (target
);
1696 /* Parse a function type. */
1699 rust_parser::parse_function_type ()
1703 if (current_token
!= '(')
1704 error (_("'(' expected"));
1706 std::vector
<struct type
*> types
= parse_maybe_type_list ();
1708 if (current_token
!= ARROW
)
1709 error (_("'->' expected"));
1712 struct type
*result_type
= parse_type ();
1714 struct type
**argtypes
= nullptr;
1715 if (!types
.empty ())
1716 argtypes
= types
.data ();
1718 result_type
= lookup_function_type_with_arguments (result_type
,
1721 return lookup_pointer_type (result_type
);
1724 /* Parse a tuple type. */
1727 rust_parser::parse_tuple_type ()
1729 std::vector
<struct type
*> types
= parse_maybe_type_list ();
1731 auto_obstack obstack
;
1732 obstack_1grow (&obstack
, '(');
1733 for (int i
= 0; i
< types
.size (); ++i
)
1735 std::string type_name
= type_to_string (types
[i
]);
1738 obstack_1grow (&obstack
, ',');
1739 obstack_grow_str (&obstack
, type_name
.c_str ());
1742 obstack_grow_str0 (&obstack
, ")");
1743 const char *name
= (const char *) obstack_finish (&obstack
);
1745 /* We don't allow creating new tuple types (yet), but we do allow
1746 looking up existing tuple types. */
1747 struct type
*result
= rust_lookup_type (name
);
1748 if (result
== nullptr)
1749 error (_("could not find tuple type '%s'"), name
);
1757 rust_parser::parse_type ()
1759 switch (current_token
)
1762 return parse_array_type ();
1764 return parse_slice_type ();
1766 return parse_pointer_type ();
1768 return parse_function_type ();
1770 return parse_tuple_type ();
1777 std::string path
= parse_path (false);
1778 struct type
*result
= rust_lookup_type (path
.c_str ());
1779 if (result
== nullptr)
1780 error (_("No type name '%s' in current context"), path
.c_str ());
1784 error (_("type expected"));
1791 rust_parser::parse_path (bool for_expr
)
1793 unsigned n_supers
= 0;
1794 int first_token
= current_token
;
1796 switch (current_token
)
1800 if (current_token
!= COLONCOLON
)
1805 while (current_token
== KW_SUPER
)
1809 if (current_token
!= COLONCOLON
)
1810 error (_("'::' expected"));
1820 /* This is a gdb extension to make it possible to refer to items
1821 in other crates. It just bypasses adding the current crate
1822 to the front of the name. */
1827 if (current_token
!= IDENT
)
1828 error (_("identifier expected"));
1829 std::string path
= get_string ();
1830 bool saw_ident
= true;
1833 /* The condition here lets us enter the loop even if we see
1835 while (current_token
== COLONCOLON
|| current_token
== '<')
1837 if (current_token
== COLONCOLON
)
1842 if (current_token
== IDENT
)
1844 path
= path
+ "::" + get_string ();
1848 else if (current_token
== COLONCOLON
)
1850 /* The code below won't detect this scenario. */
1851 error (_("unexpected '::'"));
1855 if (current_token
!= '<')
1858 /* Expression use name::<...>, whereas types use name<...>. */
1861 /* Expressions use "name::<...>", so if we saw an identifier
1862 after the "::", we ignore the "<" here. */
1868 /* Types use "name<...>", so we need to have seen the
1875 std::vector
<struct type
*> types
= parse_type_list ();
1876 if (current_token
== '>')
1878 else if (current_token
== RSH
)
1884 error (_("'>' expected"));
1887 for (int i
= 0; i
< types
.size (); ++i
)
1891 path
+= type_to_string (types
[i
]);
1897 switch (first_token
)
1901 return super_name (path
, n_supers
);
1904 return crate_name (path
);
1913 gdb_assert_not_reached ("missing case in path parsing");
1917 /* Handle the parsing for a string expression. */
1920 rust_parser::parse_string ()
1922 gdb_assert (current_token
== STRING
);
1924 /* Wrap the raw string in the &str struct. */
1925 struct type
*type
= rust_lookup_type ("&str");
1926 if (type
== nullptr)
1927 error (_("Could not find type '&str'"));
1929 std::vector
<std::pair
<std::string
, operation_up
>> field_v
;
1931 size_t len
= current_string_val
.length
;
1932 operation_up str
= make_operation
<string_operation
> (get_string ());
1934 = make_operation
<rust_unop_addr_operation
> (std::move (str
));
1935 field_v
.emplace_back ("data_ptr", std::move (addr
));
1937 struct type
*valtype
= get_type ("usize");
1938 operation_up lenop
= make_operation
<long_const_operation
> (valtype
, len
);
1939 field_v
.emplace_back ("length", std::move (lenop
));
1941 return make_operation
<rust_aggregate_operation
> (type
,
1943 std::move (field_v
));
1946 /* Parse a tuple struct expression. */
1949 rust_parser::parse_tuple_struct (struct type
*type
)
1951 std::vector
<operation_up
> args
= parse_paren_args ();
1953 std::vector
<std::pair
<std::string
, operation_up
>> field_v (args
.size ());
1954 for (int i
= 0; i
< args
.size (); ++i
)
1955 field_v
[i
] = { string_printf ("__%d", i
), std::move (args
[i
]) };
1957 return (make_operation
<rust_aggregate_operation
>
1958 (type
, operation_up (), std::move (field_v
)));
1961 /* Parse a path expression. */
1964 rust_parser::parse_path_expr ()
1966 std::string path
= parse_path (true);
1968 if (current_token
== '{')
1970 struct type
*type
= rust_lookup_type (path
.c_str ());
1971 if (type
== nullptr)
1972 error (_("Could not find type '%s'"), path
.c_str ());
1974 return parse_struct_expr (type
);
1976 else if (current_token
== '(')
1978 struct type
*type
= rust_lookup_type (path
.c_str ());
1979 /* If this is actually a tuple struct expression, handle it
1980 here. If it is a call, it will be handled elsewhere. */
1981 if (type
!= nullptr)
1983 if (!rust_tuple_struct_type_p (type
))
1984 error (_("Type %s is not a tuple struct"), path
.c_str ());
1985 return parse_tuple_struct (type
);
1989 return name_to_operation (path
);
1992 /* Parse an atom. "Atom" isn't a Rust term, but this refers to a
1993 single unitary item in the grammar; but here including some unary
1994 prefix and postfix expressions. */
1997 rust_parser::parse_atom (bool required
)
1999 operation_up result
;
2001 switch (current_token
)
2004 result
= parse_tuple ();
2008 result
= parse_array ();
2012 case DECIMAL_INTEGER
:
2013 result
= make_operation
<long_const_operation
> (current_int_val
.type
,
2014 current_int_val
.val
);
2019 result
= make_operation
<float_const_operation
> (current_float_val
.type
,
2020 current_float_val
.val
);
2025 result
= parse_string ();
2030 result
= make_operation
<string_operation
> (get_string ());
2036 result
= make_operation
<bool_operation
> (current_token
== KW_TRUE
);
2041 /* This is kind of a hacky approach. */
2043 pstate
->push_dollar (current_string_val
);
2044 result
= pstate
->pop ();
2054 result
= parse_path_expr ();
2059 result
= make_operation
<rust_unop_ind_operation
> (parse_atom (true));
2063 result
= make_operation
<unary_plus_operation
> (parse_atom (true));
2067 result
= make_operation
<unary_neg_operation
> (parse_atom (true));
2071 result
= make_operation
<rust_unop_compl_operation
> (parse_atom (true));
2074 result
= parse_sizeof ();
2077 result
= parse_addr ();
2083 error (_("unexpected token"));
2086 /* Now parse suffixes. */
2089 switch (current_token
)
2092 result
= parse_field (std::move (result
));
2096 result
= parse_index (std::move (result
));
2100 result
= parse_call (std::move (result
));
2111 /* The parser as exposed to gdb. */
2114 rust_language::parser (struct parser_state
*state
) const
2116 rust_parser
parser (state
);
2118 operation_up result
;
2121 result
= parser
.parse_entry_point ();
2123 catch (const gdb_exception
&exc
)
2125 if (state
->parse_completion
)
2127 result
= std::move (parser
.completion_op
);
2128 if (result
== nullptr)
2135 state
->set_operation (std::move (result
));
2144 /* A test helper that lexes a string, expecting a single token. */
2147 rust_lex_test_one (rust_parser
*parser
, const char *input
, int expected
)
2151 parser
->reset (input
);
2153 token
= parser
->lex_one_token ();
2154 SELF_CHECK (token
== expected
);
2158 token
= parser
->lex_one_token ();
2159 SELF_CHECK (token
== 0);
2163 /* Test that INPUT lexes as the integer VALUE. */
2166 rust_lex_int_test (rust_parser
*parser
, const char *input
,
2167 ULONGEST value
, int kind
)
2169 rust_lex_test_one (parser
, input
, kind
);
2170 SELF_CHECK (parser
->current_int_val
.val
== value
);
2173 /* Test that INPUT throws an exception with text ERR. */
2176 rust_lex_exception_test (rust_parser
*parser
, const char *input
,
2181 /* The "kind" doesn't matter. */
2182 rust_lex_test_one (parser
, input
, DECIMAL_INTEGER
);
2185 catch (const gdb_exception_error
&except
)
2187 SELF_CHECK (strcmp (except
.what (), err
) == 0);
2191 /* Test that INPUT lexes as the identifier, string, or byte-string
2192 VALUE. KIND holds the expected token kind. */
2195 rust_lex_stringish_test (rust_parser
*parser
, const char *input
,
2196 const char *value
, int kind
)
2198 rust_lex_test_one (parser
, input
, kind
);
2199 SELF_CHECK (parser
->get_string () == value
);
2202 /* Helper to test that a string parses as a given token sequence. */
2205 rust_lex_test_sequence (rust_parser
*parser
, const char *input
, int len
,
2206 const int expected
[])
2210 parser
->reset (input
);
2212 for (i
= 0; i
< len
; ++i
)
2214 int token
= parser
->lex_one_token ();
2215 SELF_CHECK (token
== expected
[i
]);
2219 /* Tests for an integer-parsing corner case. */
2222 rust_lex_test_trailing_dot (rust_parser
*parser
)
2224 const int expected1
[] = { DECIMAL_INTEGER
, '.', IDENT
, '(', ')', 0 };
2225 const int expected2
[] = { INTEGER
, '.', IDENT
, '(', ')', 0 };
2226 const int expected3
[] = { FLOAT
, EQEQ
, '(', ')', 0 };
2227 const int expected4
[] = { DECIMAL_INTEGER
, DOTDOT
, DECIMAL_INTEGER
, 0 };
2229 rust_lex_test_sequence (parser
, "23.g()", ARRAY_SIZE (expected1
), expected1
);
2230 rust_lex_test_sequence (parser
, "23_0.g()", ARRAY_SIZE (expected2
),
2232 rust_lex_test_sequence (parser
, "23.==()", ARRAY_SIZE (expected3
),
2234 rust_lex_test_sequence (parser
, "23..25", ARRAY_SIZE (expected4
), expected4
);
2237 /* Tests of completion. */
2240 rust_lex_test_completion (rust_parser
*parser
)
2242 const int expected
[] = { IDENT
, '.', COMPLETE
, 0 };
2244 parser
->pstate
->parse_completion
= 1;
2246 rust_lex_test_sequence (parser
, "something.wha", ARRAY_SIZE (expected
),
2248 rust_lex_test_sequence (parser
, "something.", ARRAY_SIZE (expected
),
2251 parser
->pstate
->parse_completion
= 0;
2254 /* Test pushback. */
2257 rust_lex_test_push_back (rust_parser
*parser
)
2261 parser
->reset (">>=");
2263 token
= parser
->lex_one_token ();
2264 SELF_CHECK (token
== COMPOUND_ASSIGN
);
2265 SELF_CHECK (parser
->current_opcode
== BINOP_RSH
);
2267 parser
->push_back ('=');
2269 token
= parser
->lex_one_token ();
2270 SELF_CHECK (token
== '=');
2272 token
= parser
->lex_one_token ();
2273 SELF_CHECK (token
== 0);
2276 /* Unit test the lexer. */
2279 rust_lex_tests (void)
2281 /* Set up dummy "parser", so that rust_type works. */
2282 struct parser_state
ps (language_def (language_rust
), target_gdbarch (),
2283 nullptr, 0, 0, nullptr, 0, nullptr, false);
2284 rust_parser
parser (&ps
);
2286 rust_lex_test_one (&parser
, "", 0);
2287 rust_lex_test_one (&parser
, " \t \n \r ", 0);
2288 rust_lex_test_one (&parser
, "thread 23", 0);
2289 rust_lex_test_one (&parser
, "task 23", 0);
2290 rust_lex_test_one (&parser
, "th 104", 0);
2291 rust_lex_test_one (&parser
, "ta 97", 0);
2293 rust_lex_int_test (&parser
, "'z'", 'z', INTEGER
);
2294 rust_lex_int_test (&parser
, "'\\xff'", 0xff, INTEGER
);
2295 rust_lex_int_test (&parser
, "'\\u{1016f}'", 0x1016f, INTEGER
);
2296 rust_lex_int_test (&parser
, "b'z'", 'z', INTEGER
);
2297 rust_lex_int_test (&parser
, "b'\\xfe'", 0xfe, INTEGER
);
2298 rust_lex_int_test (&parser
, "b'\\xFE'", 0xfe, INTEGER
);
2299 rust_lex_int_test (&parser
, "b'\\xfE'", 0xfe, INTEGER
);
2301 /* Test all escapes in both modes. */
2302 rust_lex_int_test (&parser
, "'\\n'", '\n', INTEGER
);
2303 rust_lex_int_test (&parser
, "'\\r'", '\r', INTEGER
);
2304 rust_lex_int_test (&parser
, "'\\t'", '\t', INTEGER
);
2305 rust_lex_int_test (&parser
, "'\\\\'", '\\', INTEGER
);
2306 rust_lex_int_test (&parser
, "'\\0'", '\0', INTEGER
);
2307 rust_lex_int_test (&parser
, "'\\''", '\'', INTEGER
);
2308 rust_lex_int_test (&parser
, "'\\\"'", '"', INTEGER
);
2310 rust_lex_int_test (&parser
, "b'\\n'", '\n', INTEGER
);
2311 rust_lex_int_test (&parser
, "b'\\r'", '\r', INTEGER
);
2312 rust_lex_int_test (&parser
, "b'\\t'", '\t', INTEGER
);
2313 rust_lex_int_test (&parser
, "b'\\\\'", '\\', INTEGER
);
2314 rust_lex_int_test (&parser
, "b'\\0'", '\0', INTEGER
);
2315 rust_lex_int_test (&parser
, "b'\\''", '\'', INTEGER
);
2316 rust_lex_int_test (&parser
, "b'\\\"'", '"', INTEGER
);
2318 rust_lex_exception_test (&parser
, "'z", "Unterminated character literal");
2319 rust_lex_exception_test (&parser
, "b'\\x0'", "Not enough hex digits seen");
2320 rust_lex_exception_test (&parser
, "b'\\u{0}'",
2321 "Unicode escape in byte literal");
2322 rust_lex_exception_test (&parser
, "'\\x0'", "Not enough hex digits seen");
2323 rust_lex_exception_test (&parser
, "'\\u0'", "Missing '{' in Unicode escape");
2324 rust_lex_exception_test (&parser
, "'\\u{0", "Missing '}' in Unicode escape");
2325 rust_lex_exception_test (&parser
, "'\\u{0000007}", "Overlong hex escape");
2326 rust_lex_exception_test (&parser
, "'\\u{}", "Not enough hex digits seen");
2327 rust_lex_exception_test (&parser
, "'\\Q'", "Invalid escape \\Q in literal");
2328 rust_lex_exception_test (&parser
, "b'\\Q'", "Invalid escape \\Q in literal");
2330 rust_lex_int_test (&parser
, "23", 23, DECIMAL_INTEGER
);
2331 rust_lex_int_test (&parser
, "2_344__29", 234429, INTEGER
);
2332 rust_lex_int_test (&parser
, "0x1f", 0x1f, INTEGER
);
2333 rust_lex_int_test (&parser
, "23usize", 23, INTEGER
);
2334 rust_lex_int_test (&parser
, "23i32", 23, INTEGER
);
2335 rust_lex_int_test (&parser
, "0x1_f", 0x1f, INTEGER
);
2336 rust_lex_int_test (&parser
, "0b1_101011__", 0x6b, INTEGER
);
2337 rust_lex_int_test (&parser
, "0o001177i64", 639, INTEGER
);
2338 rust_lex_int_test (&parser
, "0x123456789u64", 0x123456789ull
, INTEGER
);
2340 rust_lex_test_trailing_dot (&parser
);
2342 rust_lex_test_one (&parser
, "23.", FLOAT
);
2343 rust_lex_test_one (&parser
, "23.99f32", FLOAT
);
2344 rust_lex_test_one (&parser
, "23e7", FLOAT
);
2345 rust_lex_test_one (&parser
, "23E-7", FLOAT
);
2346 rust_lex_test_one (&parser
, "23e+7", FLOAT
);
2347 rust_lex_test_one (&parser
, "23.99e+7f64", FLOAT
);
2348 rust_lex_test_one (&parser
, "23.82f32", FLOAT
);
2350 rust_lex_stringish_test (&parser
, "hibob", "hibob", IDENT
);
2351 rust_lex_stringish_test (&parser
, "hibob__93", "hibob__93", IDENT
);
2352 rust_lex_stringish_test (&parser
, "thread", "thread", IDENT
);
2353 rust_lex_stringish_test (&parser
, "r#true", "true", IDENT
);
2355 const int expected1
[] = { IDENT
, DECIMAL_INTEGER
, 0 };
2356 rust_lex_test_sequence (&parser
, "r#thread 23", ARRAY_SIZE (expected1
),
2358 const int expected2
[] = { IDENT
, '#', 0 };
2359 rust_lex_test_sequence (&parser
, "r#", ARRAY_SIZE (expected2
), expected2
);
2361 rust_lex_stringish_test (&parser
, "\"string\"", "string", STRING
);
2362 rust_lex_stringish_test (&parser
, "\"str\\ting\"", "str\ting", STRING
);
2363 rust_lex_stringish_test (&parser
, "\"str\\\"ing\"", "str\"ing", STRING
);
2364 rust_lex_stringish_test (&parser
, "r\"str\\ing\"", "str\\ing", STRING
);
2365 rust_lex_stringish_test (&parser
, "r#\"str\\ting\"#", "str\\ting", STRING
);
2366 rust_lex_stringish_test (&parser
, "r###\"str\\\"ing\"###", "str\\\"ing",
2369 rust_lex_stringish_test (&parser
, "b\"string\"", "string", BYTESTRING
);
2370 rust_lex_stringish_test (&parser
, "b\"\x73tring\"", "string", BYTESTRING
);
2371 rust_lex_stringish_test (&parser
, "b\"str\\\"ing\"", "str\"ing", BYTESTRING
);
2372 rust_lex_stringish_test (&parser
, "br####\"\\x73tring\"####", "\\x73tring",
2375 for (const auto &candidate
: identifier_tokens
)
2376 rust_lex_test_one (&parser
, candidate
.name
, candidate
.value
);
2378 for (const auto &candidate
: operator_tokens
)
2379 rust_lex_test_one (&parser
, candidate
.name
, candidate
.value
);
2381 rust_lex_test_completion (&parser
);
2382 rust_lex_test_push_back (&parser
);
2385 #endif /* GDB_SELF_TEST */
2389 void _initialize_rust_exp ();
2391 _initialize_rust_exp ()
2393 int code
= regcomp (&number_regex
, number_regex_text
, REG_EXTENDED
);
2394 /* If the regular expression was incorrect, it was a programming
2396 gdb_assert (code
== 0);
2399 selftests::register_test ("rust-lex", rust_lex_tests
);