1 /* Parse expressions for GDB.
3 Copyright (C) 1986-2024 Free Software Foundation, Inc.
5 Modified from expread.y by the Department of Computer Science at the
6 State University of New York at Buffalo, 1991.
8 This file is part of GDB.
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>. */
23 /* Parse an expression from text in a string,
24 and return the result as a struct expression pointer.
25 That structure contains arithmetic operations in reverse polish,
26 with constants represented by operations that are followed by special data.
27 See expression.h for the details of the format.
28 What is important here is that it can be built up sequentially
29 during the process of parsing; the lower levels of the tree always
30 come first in the result. */
33 #include "arch-utils.h"
37 #include "expression.h"
41 #include "parser-defs.h"
42 #include "cli/cli-cmds.h"
45 #include "target-float.h"
49 #include "user-regs.h"
54 static unsigned int expressiondebug
= 0;
56 show_expressiondebug (struct ui_file
*file
, int from_tty
,
57 struct cmd_list_element
*c
, const char *value
)
59 gdb_printf (file
, _("Expression debugging is %s.\n"), value
);
63 /* True if an expression parser should set yydebug. */
64 static bool parser_debug
;
67 show_parserdebug (struct ui_file
*file
, int from_tty
,
68 struct cmd_list_element
*c
, const char *value
)
70 gdb_printf (file
, _("Parser debugging is %s.\n"), value
);
74 /* Documented at it's declaration. */
77 innermost_block_tracker::update (const struct block
*b
,
78 innermost_block_tracker_types t
)
80 if ((m_types
& t
) != 0
81 && (m_innermost_block
== NULL
82 || m_innermost_block
->contains (b
)))
83 m_innermost_block
= b
;
89 expr_complete_tag::complete (struct expression
*exp
,
90 completion_tracker
&tracker
)
92 collect_symbol_completion_matches_type (tracker
, m_name
.get (),
93 m_name
.get (), m_code
);
97 /* See parser-defs.h. */
100 parser_state::mark_struct_expression (expr::structop_base_operation
*op
)
102 gdb_assert (parse_completion
&& m_completion_state
== nullptr);
103 m_completion_state
= std::make_unique
<expr_complete_structop
> (op
);
106 /* Indicate that the current parser invocation is completing a tag.
107 TAG is the type code of the tag, and PTR and LENGTH represent the
108 start of the tag name. */
111 parser_state::mark_completion_tag (enum type_code tag
, const char *ptr
,
114 gdb_assert (parse_completion
&& m_completion_state
== nullptr);
115 gdb_assert (tag
== TYPE_CODE_UNION
116 || tag
== TYPE_CODE_STRUCT
117 || tag
== TYPE_CODE_ENUM
);
118 m_completion_state
.reset
119 (new expr_complete_tag (tag
, make_unique_xstrndup (ptr
, length
)));
122 /* See parser-defs.h. */
125 parser_state::push_c_string (int kind
, struct stoken_vector
*vec
)
127 std::vector
<std::string
> data (vec
->len
);
128 for (int i
= 0; i
< vec
->len
; ++i
)
129 data
[i
] = std::string (vec
->tokens
[i
].ptr
, vec
->tokens
[i
].length
);
131 push_new
<expr::c_string_operation
> ((enum c_string_type_values
) kind
,
135 /* See parser-defs.h. */
138 parser_state::push_symbol (const char *name
, block_symbol sym
)
140 if (sym
.symbol
!= nullptr)
142 if (symbol_read_needs_frame (sym
.symbol
))
143 block_tracker
->update (sym
);
144 push_new
<expr::var_value_operation
> (sym
);
148 bound_minimal_symbol msymbol
149 = lookup_minimal_symbol (current_program_space
, name
);
150 if (msymbol
.minsym
!= NULL
)
151 push_new
<expr::var_msym_value_operation
> (msymbol
);
152 else if (!have_full_symbols (current_program_space
)
153 && !have_partial_symbols (current_program_space
))
154 error (_("No symbol table is loaded. Use the \"file\" command."));
156 error (_("No symbol \"%s\" in current context."), name
);
160 /* See parser-defs.h. */
163 parser_state::push_dollar (struct stoken str
)
165 struct block_symbol sym
;
166 struct internalvar
*isym
= NULL
;
169 /* Handle the tokens $digits; also $ (short for $0) and $$ (short for $$1)
170 and $$digits (equivalent to $<-digits> if you could type that). */
174 /* Double dollar means negate the number and add -1 as well.
175 Thus $$ alone means -1. */
176 if (str
.length
>= 2 && str
.ptr
[1] == '$')
183 /* Just dollars (one or two). */
185 push_new
<expr::last_operation
> (i
);
188 /* Is the rest of the token digits? */
189 for (; i
< str
.length
; i
++)
190 if (!(str
.ptr
[i
] >= '0' && str
.ptr
[i
] <= '9'))
194 i
= atoi (str
.ptr
+ 1 + negate
);
197 push_new
<expr::last_operation
> (i
);
201 /* Handle tokens that refer to machine registers:
202 $ followed by a register name. */
203 i
= user_reg_map_name_to_regnum (gdbarch (),
204 str
.ptr
+ 1, str
.length
- 1);
209 push_new
<expr::register_operation
> (copy_name (str
));
210 block_tracker
->update (expression_context_block
,
211 INNERMOST_BLOCK_FOR_REGISTERS
);
215 /* Any names starting with $ are probably debugger internal variables. */
217 copy
= copy_name (str
);
218 isym
= lookup_only_internalvar (copy
.c_str () + 1);
221 push_new
<expr::internalvar_operation
> (isym
);
225 /* On some systems, such as HP-UX and hppa-linux, certain system routines
226 have names beginning with $ or $$. Check for those, first. */
228 sym
= lookup_symbol (copy
.c_str (), nullptr,
229 SEARCH_VAR_DOMAIN
| SEARCH_FUNCTION_DOMAIN
, nullptr);
232 push_new
<expr::var_value_operation
> (sym
);
235 bound_minimal_symbol msym
236 = lookup_minimal_symbol (current_program_space
, copy
.c_str ());
239 push_new
<expr::var_msym_value_operation
> (msym
);
243 /* Any other names are assumed to be debugger internal variables. */
245 push_new
<expr::internalvar_operation
>
246 (create_internalvar (copy
.c_str () + 1));
249 /* See parser-defs.h. */
252 parser_state::parse_error (const char *msg
)
254 if (this->prev_lexptr
)
255 this->lexptr
= this->prev_lexptr
;
257 if (*this->lexptr
== '\0')
258 error (_("A %s in expression, near the end of `%s'."),
259 msg
, this->start_of_input
);
261 error (_("A %s in expression, near `%s'."), msg
, this->lexptr
);
267 find_template_name_end (const char *p
)
270 int just_seen_right
= 0;
271 int just_seen_colon
= 0;
272 int just_seen_space
= 0;
274 if (!p
|| (*p
!= '<'))
285 /* In future, may want to allow these?? */
288 depth
++; /* start nested template */
289 if (just_seen_colon
|| just_seen_right
|| just_seen_space
)
290 return 0; /* but not after : or :: or > or space */
293 if (just_seen_colon
|| just_seen_right
)
294 return 0; /* end a (nested?) template */
295 just_seen_right
= 1; /* but not after : or :: */
296 if (--depth
== 0) /* also disallow >>, insist on > > */
297 return ++p
; /* if outermost ended, return */
300 if (just_seen_space
|| (just_seen_colon
> 1))
301 return 0; /* nested class spec coming up */
302 just_seen_colon
++; /* we allow :: but not :::: */
307 if (!((*p
>= 'a' && *p
<= 'z') || /* allow token chars */
308 (*p
>= 'A' && *p
<= 'Z') ||
309 (*p
>= '0' && *p
<= '9') ||
310 (*p
== '_') || (*p
== ',') || /* commas for template args */
311 (*p
== '&') || (*p
== '*') || /* pointer and ref types */
312 (*p
== '(') || (*p
== ')') || /* function types */
313 (*p
== '[') || (*p
== ']'))) /* array types */
327 /* Return a null-terminated temporary copy of the name of a string token.
329 Tokens that refer to names do so with explicit pointer and length,
330 so they can share the storage that lexptr is parsing.
331 When it is necessary to pass a name to a function that expects
332 a null-terminated string, the substring is copied out
333 into a separate block of storage. */
336 copy_name (struct stoken token
)
338 return std::string (token
.ptr
, token
.length
);
342 /* As for parse_exp_1, except that if VOID_CONTEXT_P, then
343 no value is expected from the expression. */
346 parse_exp_in_context (const char **stringptr
, CORE_ADDR pc
,
347 const struct block
*block
,
349 innermost_block_tracker
*tracker
,
350 std::unique_ptr
<expr_completion_base
> *completer
)
352 const struct language_defn
*lang
= NULL
;
354 if (*stringptr
== 0 || **stringptr
== 0)
355 error_no_arg (_("expression to compute"));
357 const struct block
*expression_context_block
= block
;
358 CORE_ADDR expression_context_pc
= 0;
360 innermost_block_tracker local_tracker
;
361 if (tracker
== nullptr)
362 tracker
= &local_tracker
;
364 if ((flags
& PARSER_LEAVE_BLOCK_ALONE
) == 0)
366 /* If no context specified, try using the current frame, if any. */
367 if (!expression_context_block
)
368 expression_context_block
369 = get_selected_block (&expression_context_pc
);
371 expression_context_pc
= expression_context_block
->entry_pc ();
373 expression_context_pc
= pc
;
375 /* Fall back to using the current source static context, if any. */
377 if (!expression_context_block
)
379 symtab_and_line cursal
380 = get_current_source_symtab_and_line (current_program_space
);
383 expression_context_block
384 = cursal
.symtab
->compunit ()->blockvector ()->static_block ();
386 if (expression_context_block
)
387 expression_context_pc
= expression_context_block
->entry_pc ();
391 if (language_mode
== language_mode_auto
&& block
!= NULL
)
393 /* Find the language associated to the given context block.
394 Default to the current language if it can not be determined.
396 Note that using the language corresponding to the current frame
397 can sometimes give unexpected results. For instance, this
398 routine is often called several times during the inferior
399 startup phase to re-parse breakpoint expressions after
400 a new shared library has been loaded. The language associated
401 to the current frame at this moment is not relevant for
402 the breakpoint. Using it would therefore be silly, so it seems
403 better to rely on the current language rather than relying on
404 the current frame language to parse the expression. That's why
405 we do the following language detection only if the context block
406 has been specifically provided. */
407 struct symbol
*func
= block
->linkage_function ();
410 lang
= language_def (func
->language ());
411 if (lang
== NULL
|| lang
->la_language
== language_unknown
)
412 lang
= current_language
;
415 lang
= current_language
;
417 /* get_current_arch may reset CURRENT_LANGUAGE via select_frame.
418 While we need CURRENT_LANGUAGE to be set to LANG (for lookup_symbol
419 and others called from *.y) ensure CURRENT_LANGUAGE gets restored
420 to the value matching SELECTED_FRAME as set by get_current_arch. */
422 parser_state
ps (lang
, get_current_arch (), expression_context_block
,
423 expression_context_pc
, flags
, *stringptr
,
424 completer
!= nullptr, tracker
);
426 scoped_restore_current_language
lang_saver (lang
->la_language
);
432 catch (const gdb_exception_error
&except
)
434 /* If parsing for completion, allow this to succeed; but if no
435 expression elements have been written, then there's nothing
437 if (! ps
.parse_completion
|| ps
.expout
->op
== nullptr)
441 expression_up result
= ps
.release ();
442 result
->op
->set_outermost ();
445 result
->dump (gdb_stdlog
);
447 if (completer
!= nullptr)
448 *completer
= std::move (ps
.m_completion_state
);
449 *stringptr
= ps
.lexptr
;
453 /* Read an expression from the string *STRINGPTR points to,
454 parse it, and return a pointer to a struct expression that we malloc.
455 Use block BLOCK as the lexical context for variable names;
456 if BLOCK is zero, use the block of the selected stack frame.
457 Meanwhile, advance *STRINGPTR to point after the expression,
458 at the first nonwhite character that is not part of the expression
459 (possibly a null character). FLAGS are passed to the parser. */
462 parse_exp_1 (const char **stringptr
, CORE_ADDR pc
, const struct block
*block
,
463 parser_flags flags
, innermost_block_tracker
*tracker
)
465 return parse_exp_in_context (stringptr
, pc
, block
, flags
,
469 /* Parse STRING as an expression, and complain if this fails to use up
470 all of the contents of STRING. TRACKER, if non-null, will be
471 updated by the parser. FLAGS are passed to the parser. */
474 parse_expression (const char *string
, innermost_block_tracker
*tracker
,
477 expression_up exp
= parse_exp_in_context (&string
, 0, nullptr, flags
,
480 error (_("Junk after end of expression."));
484 /* Same as parse_expression, but using the given language (LANG)
485 to parse the expression. */
488 parse_expression_with_language (const char *string
, enum language lang
)
490 std::optional
<scoped_restore_current_language
> lang_saver
;
491 if (current_language
->la_language
!= lang
)
492 lang_saver
.emplace (lang
);
494 return parse_expression (string
);
497 /* Parse STRING as an expression. If the parse is marked for
498 completion, set COMPLETER and return the expression. In all other
499 cases, return NULL. */
502 parse_expression_for_completion
504 std::unique_ptr
<expr_completion_base
> *completer
)
510 exp
= parse_exp_in_context (&string
, 0, 0, 0, nullptr, completer
);
512 catch (const gdb_exception_error
&except
)
514 /* Nothing, EXP remains NULL. */
517 /* If we didn't get a completion result, be sure to also not return
518 an expression to our caller. */
519 if (*completer
== nullptr)
525 /* Parse floating point value P of length LEN.
526 Return false if invalid, true if valid.
527 The successfully parsed number is stored in DATA in
528 target format for floating-point type TYPE.
530 NOTE: This accepts the floating point syntax that sscanf accepts. */
533 parse_float (const char *p
, int len
,
534 const struct type
*type
, gdb_byte
*data
)
536 return target_float_from_string (data
, type
, std::string (p
, len
));
539 /* Return true if the number N_SIGN * N fits in a type with TYPE_BITS and
540 TYPE_SIGNED_P. N_SIGNED is either 1 or -1. */
543 fits_in_type (int n_sign
, ULONGEST n
, int type_bits
, bool type_signed_p
)
546 if (n
== 0 && n_sign
== -1)
549 if (n_sign
== -1 && !type_signed_p
)
550 /* Can't fit a negative number in an unsigned type. */
553 if (type_bits
> sizeof (ULONGEST
) * 8)
556 ULONGEST smax
= (ULONGEST
)1 << (type_bits
- 1);
559 /* Negative number, signed type. */
562 else if (n_sign
== 1 && type_signed_p
)
564 /* Positive number, signed type. */
567 else if (n_sign
== 1 && !type_signed_p
)
569 /* Positive number, unsigned type. */
570 return ((n
>> 1) >> (type_bits
- 1)) == 0;
573 gdb_assert_not_reached ("");
576 /* Return true if the number N_SIGN * N fits in a type with TYPE_BITS and
577 TYPE_SIGNED_P. N_SIGNED is either 1 or -1. */
580 fits_in_type (int n_sign
, const gdb_mpz
&n
, int type_bits
, bool type_signed_p
)
582 /* N must be nonnegative. */
583 gdb_assert (n
.sgn () >= 0);
585 /* Zero always fits. */
590 if (n_sign
== -1 && !type_signed_p
)
591 /* Can't fit a negative number in an unsigned type. */
594 gdb_mpz max
= gdb_mpz::pow (2, (type_signed_p
602 /* This function avoids direct calls to fprintf
603 in the parser generated debug code. */
605 parser_fprintf (FILE *x
, const char *y
, ...)
611 gdb_vprintf (gdb_stderr
, y
, args
);
614 gdb_printf (gdb_stderr
, " Unknown FILE used.\n");
615 gdb_vprintf (gdb_stderr
, y
, args
);
620 void _initialize_parse ();
624 add_setshow_zuinteger_cmd ("expression", class_maintenance
,
626 _("Set expression debugging."),
627 _("Show expression debugging."),
628 _("When non-zero, the internal representation "
629 "of expressions will be printed."),
631 show_expressiondebug
,
632 &setdebuglist
, &showdebuglist
);
633 add_setshow_boolean_cmd ("parser", class_maintenance
,
635 _("Set parser debugging."),
636 _("Show parser debugging."),
637 _("When non-zero, expression parser "
638 "tracing will be enabled."),
641 &setdebuglist
, &showdebuglist
);