1 /* YACC parser for Go expressions, for GDB.
3 Copyright (C) 2012-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/>. */
20 /* This file is derived from c-exp.y, p-exp.y. */
22 /* Parse a Go expression from text in a string,
23 and return the result as a struct expression pointer.
24 That structure contains arithmetic operations in reverse polish,
25 with constants represented by operations that are followed by special data.
26 See expression.h for the details of the format.
27 What is important here is that it can be built up sequentially
28 during the process of parsing; the lower levels of the tree always
29 come first in the result.
31 Note that malloc's and realloc's in this file are transformed to
32 xmalloc and xrealloc respectively by the same sed command in the
33 makefile that remaps any other malloc/realloc inserted by the parser
34 generator. Doing this with #defines and trying to control the interaction
35 with include files (<malloc.h> and <stdlib.h> for example) just became
36 too messy, particularly when such includes can be inserted at random
37 times by the parser generator. */
39 /* Known bugs or limitations:
43 - '_' (blank identifier)
44 - automatic deref of pointers
46 - interfaces, channels, etc.
48 And lots of other things.
49 I'm sure there's some cleanup to do.
56 #include "expression.h"
58 #include "parser-defs.h"
62 #include "bfd.h" /* Required by objfiles.h. */
63 #include "symfile.h" /* Required by objfiles.h. */
64 #include "objfiles.h" /* For have_full_symbols and have_partial_symbols */
69 #define parse_type(ps) builtin_type (ps->gdbarch ())
71 /* Remap normal yacc parser interface names (yyparse, yylex, yyerror,
73 #define GDB_YY_REMAP_PREFIX go_
76 /* The state of the parser, used internally when we are parsing the
79 static struct parser_state *pstate = NULL;
83 static int yylex (void);
85 static void yyerror (const char *);
89 /* Although the yacc "value" of an expression is not used,
90 since the result is stored in the structure being created,
91 other node types do have values. */
105 struct symtoken ssym;
107 struct typed_stoken tsval;
110 enum exp_opcode opcode;
111 struct internalvar *ivar;
112 struct stoken_vector svec;
116 /* YYSTYPE gets defined by %union. */
117 static int parse_number (struct parser_state *,
118 const char *, int, int, YYSTYPE *);
120 using namespace expr;
123 %type <voidval> exp exp1 type_exp start variable lcurly
127 %token <typed_val_int> INT
128 %token <typed_val_float> FLOAT
130 /* Both NAME and TYPENAME tokens represent symbols in the input,
131 and both convey their data as strings.
132 But a TYPENAME is a string that happens to be defined as a type
133 or builtin type name (such as int or char)
134 and a NAME is any other symbol.
135 Contexts where this distinction is not important can use the
136 nonterminal "name", which matches either NAME or TYPENAME. */
138 %token <tsval> RAW_STRING
139 %token <tsval> STRING
142 %token <tsym> TYPENAME /* Not TYPE_NAME cus already taken. */
143 %token <voidval> COMPLETE
144 /*%type <sval> name*/
145 %type <svec> string_exp
146 %type <ssym> name_not_typename
148 /* A NAME_OR_INT is a symbol which is not known in the symbol table,
149 but which would parse as a valid number in the current input radix.
150 E.g. "c" when input_radix==16. Depending on the parse, it will be
151 turned into a name or into a number. */
152 %token <ssym> NAME_OR_INT
154 %token <lval> TRUE_KEYWORD FALSE_KEYWORD
155 %token STRUCT_KEYWORD INTERFACE_KEYWORD TYPE_KEYWORD CHAN_KEYWORD
156 %token SIZEOF_KEYWORD
157 %token LEN_KEYWORD CAP_KEYWORD
159 %token IOTA_KEYWORD NIL_KEYWORD
165 /* Special type cases. */
166 %token BYTE_KEYWORD /* An alias of uint8. */
168 %token <sval> DOLLAR_VARIABLE
170 %token <opcode> ASSIGN_MODIFY
174 %right '=' ASSIGN_MODIFY
183 %left '<' '>' LEQ GEQ
188 %right UNARY INCREMENT DECREMENT
189 %right LEFT_ARROW '.' '[' '('
199 { pstate->push_new<type_operation> ($1); }
202 /* Expressions, including the comma operator. */
205 { pstate->wrap2<comma_operation> (); }
208 /* Expressions, not including the comma operator. */
209 exp : '*' exp %prec UNARY
210 { pstate->wrap<unop_ind_operation> (); }
213 exp : '&' exp %prec UNARY
214 { pstate->wrap<unop_addr_operation> (); }
217 exp : '-' exp %prec UNARY
218 { pstate->wrap<unary_neg_operation> (); }
221 exp : '+' exp %prec UNARY
222 { pstate->wrap<unary_plus_operation> (); }
225 exp : '!' exp %prec UNARY
226 { pstate->wrap<unary_logical_not_operation> (); }
229 exp : '^' exp %prec UNARY
230 { pstate->wrap<unary_complement_operation> (); }
233 exp : exp INCREMENT %prec UNARY
234 { pstate->wrap<postinc_operation> (); }
237 exp : exp DECREMENT %prec UNARY
238 { pstate->wrap<postdec_operation> (); }
241 /* foo->bar is not in Go. May want as a gdb extension. Later. */
243 exp : exp '.' name_not_typename
245 pstate->push_new<structop_operation>
246 (pstate->pop (), copy_name ($3.stoken));
250 exp : exp '.' name_not_typename COMPLETE
252 structop_base_operation *op
253 = new structop_operation (pstate->pop (),
254 copy_name ($3.stoken));
255 pstate->mark_struct_expression (op);
256 pstate->push (operation_up (op));
260 exp : exp '.' COMPLETE
262 structop_base_operation *op
263 = new structop_operation (pstate->pop (), "");
264 pstate->mark_struct_expression (op);
265 pstate->push (operation_up (op));
269 exp : exp '[' exp1 ']'
270 { pstate->wrap2<subscript_operation> (); }
274 /* This is to save the value of arglist_len
275 being accumulated by an outer function call. */
276 { pstate->start_arglist (); }
277 arglist ')' %prec LEFT_ARROW
279 std::vector<operation_up> args
280 = pstate->pop_vector (pstate->end_arglist ());
281 pstate->push_new<funcall_operation>
282 (pstate->pop (), std::move (args));
287 { pstate->start_arglist (); }
294 { pstate->arglist_len = 1; }
297 arglist : arglist ',' exp %prec ABOVE_COMMA
298 { pstate->arglist_len++; }
302 { $$ = pstate->end_arglist () - 1; }
305 exp : lcurly type rcurly exp %prec UNARY
307 pstate->push_new<unop_memval_operation>
308 (pstate->pop (), $2);
312 exp : type '(' exp ')' %prec UNARY
314 pstate->push_new<unop_cast_operation>
315 (pstate->pop (), $1);
323 /* Binary operators in order of decreasing precedence. */
326 { pstate->wrap2<repeat_operation> (); }
330 { pstate->wrap2<mul_operation> (); }
334 { pstate->wrap2<div_operation> (); }
338 { pstate->wrap2<rem_operation> (); }
342 { pstate->wrap2<add_operation> (); }
346 { pstate->wrap2<sub_operation> (); }
350 { pstate->wrap2<lsh_operation> (); }
354 { pstate->wrap2<rsh_operation> (); }
358 { pstate->wrap2<equal_operation> (); }
361 exp : exp NOTEQUAL exp
362 { pstate->wrap2<notequal_operation> (); }
366 { pstate->wrap2<leq_operation> (); }
370 { pstate->wrap2<geq_operation> (); }
374 { pstate->wrap2<less_operation> (); }
378 { pstate->wrap2<gtr_operation> (); }
382 { pstate->wrap2<bitwise_and_operation> (); }
386 { pstate->wrap2<bitwise_xor_operation> (); }
390 { pstate->wrap2<bitwise_ior_operation> (); }
394 { pstate->wrap2<logical_and_operation> (); }
398 { pstate->wrap2<logical_or_operation> (); }
401 exp : exp '?' exp ':' exp %prec '?'
403 operation_up last = pstate->pop ();
404 operation_up mid = pstate->pop ();
405 operation_up first = pstate->pop ();
406 pstate->push_new<ternop_cond_operation>
407 (std::move (first), std::move (mid),
413 { pstate->wrap2<assign_operation> (); }
416 exp : exp ASSIGN_MODIFY exp
418 operation_up rhs = pstate->pop ();
419 operation_up lhs = pstate->pop ();
420 pstate->push_new<assign_modify_operation>
421 ($2, std::move (lhs), std::move (rhs));
427 pstate->push_new<long_const_operation>
434 struct stoken_vector vec;
437 pstate->push_c_string ($1.type, &vec);
443 parse_number (pstate, $1.stoken.ptr,
444 $1.stoken.length, 0, &val);
445 pstate->push_new<long_const_operation>
446 (val.typed_val_int.type,
447 val.typed_val_int.val);
455 std::copy (std::begin ($1.val), std::end ($1.val),
457 pstate->push_new<float_const_operation> ($1.type, data);
464 exp : DOLLAR_VARIABLE
466 pstate->push_dollar ($1);
470 exp : SIZEOF_KEYWORD '(' type ')' %prec UNARY
472 /* TODO(dje): Go objects in structs. */
473 /* TODO(dje): What's the right type here? */
474 struct type *size_type
475 = parse_type (pstate)->builtin_unsigned_int;
476 $3 = check_typedef ($3);
477 pstate->push_new<long_const_operation>
478 (size_type, (LONGEST) TYPE_LENGTH ($3));
482 exp : SIZEOF_KEYWORD '(' exp ')' %prec UNARY
484 /* TODO(dje): Go objects in structs. */
485 pstate->wrap<unop_sizeof_operation> ();
491 /* We copy the string here, and not in the
492 lexer, to guarantee that we do not leak a
494 /* Note that we NUL-terminate here, but just
496 struct typed_stoken *vec = XNEW (struct typed_stoken);
501 vec->length = $1.length;
502 vec->ptr = (char *) malloc ($1.length + 1);
503 memcpy (vec->ptr, $1.ptr, $1.length + 1);
506 | string_exp '+' STRING
508 /* Note that we NUL-terminate here, but just
512 $$.tokens = XRESIZEVEC (struct typed_stoken,
515 p = (char *) malloc ($3.length + 1);
516 memcpy (p, $3.ptr, $3.length + 1);
518 $$.tokens[$$.len - 1].type = $3.type;
519 $$.tokens[$$.len - 1].length = $3.length;
520 $$.tokens[$$.len - 1].ptr = p;
524 exp : string_exp %prec ABOVE_COMMA
529 pstate->push_c_string (0, &$1);
530 for (i = 0; i < $1.len; ++i)
531 free ($1.tokens[i].ptr);
537 { pstate->push_new<bool_operation> ($1); }
541 { pstate->push_new<bool_operation> ($1); }
544 variable: name_not_typename ENTRY
545 { struct symbol *sym = $1.sym.symbol;
548 || !sym->is_argument ()
549 || !symbol_read_needs_frame (sym))
550 error (_("@entry can be used only for function "
551 "parameters, not for \"%s\""),
552 copy_name ($1.stoken).c_str ());
554 pstate->push_new<var_entry_value_operation> (sym);
558 variable: name_not_typename
559 { struct block_symbol sym = $1.sym;
563 if (symbol_read_needs_frame (sym.symbol))
564 pstate->block_tracker->update (sym);
566 pstate->push_new<var_value_operation> (sym);
568 else if ($1.is_a_field_of_this)
570 /* TODO(dje): Can we get here?
571 E.g., via a mix of c++ and go? */
572 gdb_assert_not_reached ("go with `this' field");
576 struct bound_minimal_symbol msymbol;
577 std::string arg = copy_name ($1.stoken);
580 lookup_bound_minimal_symbol (arg.c_str ());
581 if (msymbol.minsym != NULL)
582 pstate->push_new<var_msym_value_operation>
584 else if (!have_full_symbols ()
585 && !have_partial_symbols ())
586 error (_("No symbol table is loaded. "
587 "Use the \"file\" command."));
589 error (_("No symbol \"%s\" in current context."),
596 method_exp: PACKAGENAME '.' name '.' name
602 type /* Implements (approximately): [*] type-specifier */
604 { $$ = lookup_pointer_type ($2); }
608 | STRUCT_KEYWORD name
609 { $$ = lookup_struct (copy_name ($2),
610 expression_context_block); }
613 { $$ = builtin_go_type (pstate->gdbarch ())
618 name : NAME { $$ = $1.stoken; }
619 | TYPENAME { $$ = $1.stoken; }
620 | NAME_OR_INT { $$ = $1.stoken; }
626 /* These would be useful if name_not_typename was useful, but it is just
627 a fake for "variable", so these cause reduce/reduce conflicts because
628 the parser can't tell whether NAME_OR_INT is a name_not_typename (=variable,
629 =exp) or just an exp. If name_not_typename was ever used in an lvalue
630 context where only a name could occur, this might be useful.
637 /* Take care of parsing a number (anything that starts with a digit).
638 Set yylval and return the token type; update lexptr.
639 LEN is the number of characters in it. */
641 /* FIXME: Needs some error checking for the float case. */
642 /* FIXME(dje): IWBN to use c-exp.y's parse_number if we could.
643 That will require moving the guts into a function that we both call
644 as our YYSTYPE is different than c-exp.y's */
647 parse_number (struct parser_state *par_state,
648 const char *p, int len, int parsed_float, YYSTYPE *putithere)
656 int base = input_radix;
659 /* Number of "L" suffixes encountered. */
662 /* We have found a "L" or "U" suffix. */
663 int found_suffix = 0;
666 struct type *signed_type;
667 struct type *unsigned_type;
671 const struct builtin_go_type *builtin_go_types
672 = builtin_go_type (par_state->gdbarch ());
674 /* Handle suffixes: 'f' for float32, 'l' for long double.
675 FIXME: This appears to be an extension -- do we want this? */
676 if (len >= 1 && tolower (p[len - 1]) == 'f')
678 putithere->typed_val_float.type
679 = builtin_go_types->builtin_float32;
682 else if (len >= 1 && tolower (p[len - 1]) == 'l')
684 putithere->typed_val_float.type
685 = parse_type (par_state)->builtin_long_double;
688 /* Default type for floating-point literals is float64. */
691 putithere->typed_val_float.type
692 = builtin_go_types->builtin_float64;
695 if (!parse_float (p, len,
696 putithere->typed_val_float.type,
697 putithere->typed_val_float.val))
702 /* Handle base-switching prefixes 0x, 0t, 0d, 0. */
703 if (p[0] == '0' && len > 1)
746 if (c >= 'A' && c <= 'Z')
748 if (c != 'l' && c != 'u')
750 if (c >= '0' && c <= '9')
758 if (base > 10 && c >= 'a' && c <= 'f')
762 n += i = c - 'a' + 10;
775 return ERROR; /* Char not a digit */
778 return ERROR; /* Invalid digit in this base. */
780 /* Portably test for overflow (only works for nonzero values, so make
781 a second check for zero). FIXME: Can't we just make n and prevn
782 unsigned and avoid this? */
783 if (c != 'l' && c != 'u' && (prevn >= n) && n != 0)
784 unsigned_p = 1; /* Try something unsigned. */
786 /* Portably test for unsigned overflow.
787 FIXME: This check is wrong; for example it doesn't find overflow
788 on 0x123456789 when LONGEST is 32 bits. */
789 if (c != 'l' && c != 'u' && n != 0)
791 if ((unsigned_p && prevn >= n))
792 error (_("Numeric constant too large."));
797 /* An integer constant is an int, a long, or a long long. An L
798 suffix forces it to be long; an LL suffix forces it to be long
799 long. If not forced to a larger size, it gets the first type of
800 the above that it fits in. To figure out whether it fits, we
801 shift it right and see whether anything remains. Note that we
802 can't shift sizeof (LONGEST) * HOST_CHAR_BIT bits or more in one
803 operation, because many compilers will warn about such a shift
804 (which always produces a zero result). Sometimes gdbarch_int_bit
805 or gdbarch_long_bit will be that big, sometimes not. To deal with
806 the case where it is we just always shift the value more than
807 once, with fewer bits each time. */
811 && (un >> (gdbarch_int_bit (par_state->gdbarch ()) - 2)) == 0)
814 = ((ULONGEST)1) << (gdbarch_int_bit (par_state->gdbarch ()) - 1);
816 /* A large decimal (not hex or octal) constant (between INT_MAX
817 and UINT_MAX) is a long or unsigned long, according to ANSI,
818 never an unsigned int, but this code treats it as unsigned
819 int. This probably should be fixed. GCC gives a warning on
822 unsigned_type = parse_type (par_state)->builtin_unsigned_int;
823 signed_type = parse_type (par_state)->builtin_int;
826 && (un >> (gdbarch_long_bit (par_state->gdbarch ()) - 2)) == 0)
829 = ((ULONGEST)1) << (gdbarch_long_bit (par_state->gdbarch ()) - 1);
830 unsigned_type = parse_type (par_state)->builtin_unsigned_long;
831 signed_type = parse_type (par_state)->builtin_long;
836 if (sizeof (ULONGEST) * HOST_CHAR_BIT
837 < gdbarch_long_long_bit (par_state->gdbarch ()))
838 /* A long long does not fit in a LONGEST. */
839 shift = (sizeof (ULONGEST) * HOST_CHAR_BIT - 1);
841 shift = (gdbarch_long_long_bit (par_state->gdbarch ()) - 1);
842 high_bit = (ULONGEST) 1 << shift;
843 unsigned_type = parse_type (par_state)->builtin_unsigned_long_long;
844 signed_type = parse_type (par_state)->builtin_long_long;
847 putithere->typed_val_int.val = n;
849 /* If the high bit of the worked out type is set then this number
850 has to be unsigned. */
852 if (unsigned_p || (n & high_bit))
854 putithere->typed_val_int.type = unsigned_type;
858 putithere->typed_val_int.type = signed_type;
864 /* Temporary obstack used for holding strings. */
865 static struct obstack tempbuf;
866 static int tempbuf_init;
868 /* Parse a string or character literal from TOKPTR. The string or
869 character may be wide or unicode. *OUTPTR is set to just after the
870 end of the literal in the input string. The resulting token is
871 stored in VALUE. This returns a token value, either STRING or
872 CHAR, depending on what was parsed. *HOST_CHARS is set to the
873 number of host characters in the literal. */
876 parse_string_or_char (const char *tokptr, const char **outptr,
877 struct typed_stoken *value, int *host_chars)
881 /* Build the gdb internal form of the input string in tempbuf. Note
882 that the buffer is null byte terminated *only* for the
883 convenience of debugging gdb itself and printing the buffer
884 contents when the buffer contains no embedded nulls. Gdb does
885 not depend upon the buffer being null byte terminated, it uses
886 the length string instead. This allows gdb to handle C strings
887 (as well as strings in other languages) with embedded null
893 obstack_free (&tempbuf, NULL);
894 obstack_init (&tempbuf);
896 /* Skip the quote. */
908 *host_chars += c_parse_escape (&tokptr, &tempbuf);
914 obstack_1grow (&tempbuf, c);
916 /* FIXME: this does the wrong thing with multi-byte host
917 characters. We could use mbrlen here, but that would
918 make "set host-charset" a bit less useful. */
923 if (*tokptr != quote)
926 error (_("Unterminated string in expression."));
928 error (_("Unmatched single quote."));
932 value->type = (int) C_STRING | (quote == '\'' ? C_CHAR : 0); /*FIXME*/
933 value->ptr = (char *) obstack_base (&tempbuf);
934 value->length = obstack_object_size (&tempbuf);
938 return quote == '\'' ? CHAR : STRING;
945 enum exp_opcode opcode;
948 static const struct token tokentab3[] =
950 {">>=", ASSIGN_MODIFY, BINOP_RSH},
951 {"<<=", ASSIGN_MODIFY, BINOP_LSH},
952 /*{"&^=", ASSIGN_MODIFY, BINOP_BITWISE_ANDNOT}, TODO */
953 {"...", DOTDOTDOT, OP_NULL},
956 static const struct token tokentab2[] =
958 {"+=", ASSIGN_MODIFY, BINOP_ADD},
959 {"-=", ASSIGN_MODIFY, BINOP_SUB},
960 {"*=", ASSIGN_MODIFY, BINOP_MUL},
961 {"/=", ASSIGN_MODIFY, BINOP_DIV},
962 {"%=", ASSIGN_MODIFY, BINOP_REM},
963 {"|=", ASSIGN_MODIFY, BINOP_BITWISE_IOR},
964 {"&=", ASSIGN_MODIFY, BINOP_BITWISE_AND},
965 {"^=", ASSIGN_MODIFY, BINOP_BITWISE_XOR},
966 {"++", INCREMENT, OP_NULL},
967 {"--", DECREMENT, OP_NULL},
968 /*{"->", RIGHT_ARROW, OP_NULL}, Doesn't exist in Go. */
969 {"<-", LEFT_ARROW, OP_NULL},
970 {"&&", ANDAND, OP_NULL},
971 {"||", OROR, OP_NULL},
972 {"<<", LSH, OP_NULL},
973 {">>", RSH, OP_NULL},
974 {"==", EQUAL, OP_NULL},
975 {"!=", NOTEQUAL, OP_NULL},
976 {"<=", LEQ, OP_NULL},
977 {">=", GEQ, OP_NULL},
978 /*{"&^", ANDNOT, OP_NULL}, TODO */
981 /* Identifier-like tokens. */
982 static const struct token ident_tokens[] =
984 {"true", TRUE_KEYWORD, OP_NULL},
985 {"false", FALSE_KEYWORD, OP_NULL},
986 {"nil", NIL_KEYWORD, OP_NULL},
987 {"const", CONST_KEYWORD, OP_NULL},
988 {"struct", STRUCT_KEYWORD, OP_NULL},
989 {"type", TYPE_KEYWORD, OP_NULL},
990 {"interface", INTERFACE_KEYWORD, OP_NULL},
991 {"chan", CHAN_KEYWORD, OP_NULL},
992 {"byte", BYTE_KEYWORD, OP_NULL}, /* An alias of uint8. */
993 {"len", LEN_KEYWORD, OP_NULL},
994 {"cap", CAP_KEYWORD, OP_NULL},
995 {"new", NEW_KEYWORD, OP_NULL},
996 {"iota", IOTA_KEYWORD, OP_NULL},
999 /* This is set if a NAME token appeared at the very end of the input
1000 string, with no whitespace separating the name from the EOF. This
1001 is used only when parsing to do field name completion. */
1002 static int saw_name_at_eof;
1004 /* This is set if the previously-returned token was a structure
1005 operator -- either '.' or ARROW. This is used only when parsing to
1006 do field name completion. */
1007 static int last_was_structop;
1009 /* Depth of parentheses. */
1010 static int paren_depth;
1012 /* Read one token, getting characters through lexptr. */
1015 lex_one_token (struct parser_state *par_state)
1019 const char *tokstart;
1020 int saw_structop = last_was_structop;
1022 last_was_structop = 0;
1026 par_state->prev_lexptr = par_state->lexptr;
1028 tokstart = par_state->lexptr;
1029 /* See if it is a special token of length 3. */
1030 for (const auto &token : tokentab3)
1031 if (strncmp (tokstart, token.oper, 3) == 0)
1033 par_state->lexptr += 3;
1034 yylval.opcode = token.opcode;
1038 /* See if it is a special token of length 2. */
1039 for (const auto &token : tokentab2)
1040 if (strncmp (tokstart, token.oper, 2) == 0)
1042 par_state->lexptr += 2;
1043 yylval.opcode = token.opcode;
1044 /* NOTE: -> doesn't exist in Go, so we don't need to watch for
1045 setting last_was_structop here. */
1049 switch (c = *tokstart)
1052 if (saw_name_at_eof)
1054 saw_name_at_eof = 0;
1057 else if (saw_structop)
1065 par_state->lexptr++;
1071 par_state->lexptr++;
1076 if (paren_depth == 0)
1079 par_state->lexptr++;
1083 if (pstate->comma_terminates
1084 && paren_depth == 0)
1086 par_state->lexptr++;
1090 /* Might be a floating point number. */
1091 if (par_state->lexptr[1] < '0' || par_state->lexptr[1] > '9')
1093 if (pstate->parse_completion)
1094 last_was_structop = 1;
1095 goto symbol; /* Nope, must be a symbol. */
1110 /* It's a number. */
1111 int got_dot = 0, got_e = 0, toktype;
1112 const char *p = tokstart;
1113 int hex = input_radix > 10;
1115 if (c == '0' && (p[1] == 'x' || p[1] == 'X'))
1123 /* This test includes !hex because 'e' is a valid hex digit
1124 and thus does not indicate a floating point number when
1125 the radix is hex. */
1126 if (!hex && !got_e && (*p == 'e' || *p == 'E'))
1127 got_dot = got_e = 1;
1128 /* This test does not include !hex, because a '.' always indicates
1129 a decimal floating point number regardless of the radix. */
1130 else if (!got_dot && *p == '.')
1132 else if (got_e && (p[-1] == 'e' || p[-1] == 'E')
1133 && (*p == '-' || *p == '+'))
1134 /* This is the sign of the exponent, not the end of the
1137 /* We will take any letters or digits. parse_number will
1138 complain if past the radix, or if L or U are not final. */
1139 else if ((*p < '0' || *p > '9')
1140 && ((*p < 'a' || *p > 'z')
1141 && (*p < 'A' || *p > 'Z')))
1144 toktype = parse_number (par_state, tokstart, p - tokstart,
1145 got_dot|got_e, &yylval);
1146 if (toktype == ERROR)
1148 char *err_copy = (char *) alloca (p - tokstart + 1);
1150 memcpy (err_copy, tokstart, p - tokstart);
1151 err_copy[p - tokstart] = 0;
1152 error (_("Invalid number \"%s\"."), err_copy);
1154 par_state->lexptr = p;
1160 const char *p = &tokstart[1];
1161 size_t len = strlen ("entry");
1163 while (isspace (*p))
1165 if (strncmp (p, "entry", len) == 0 && !isalnum (p[len])
1168 par_state->lexptr = &p[len];
1191 par_state->lexptr++;
1199 int result = parse_string_or_char (tokstart, &par_state->lexptr,
1200 &yylval.tsval, &host_len);
1204 error (_("Empty character constant."));
1205 else if (host_len > 2 && c == '\'')
1208 namelen = par_state->lexptr - tokstart - 1;
1211 else if (host_len > 1)
1212 error (_("Invalid character constant."));
1218 if (!(c == '_' || c == '$'
1219 || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')))
1220 /* We must have come across a bad character (e.g. ';'). */
1221 error (_("Invalid character '%c' in expression."), c);
1223 /* It's a name. See how long it is. */
1225 for (c = tokstart[namelen];
1226 (c == '_' || c == '$' || (c >= '0' && c <= '9')
1227 || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));)
1229 c = tokstart[++namelen];
1232 /* The token "if" terminates the expression and is NOT removed from
1233 the input stream. It doesn't count if it appears in the
1234 expansion of a macro. */
1236 && tokstart[0] == 'i'
1237 && tokstart[1] == 'f')
1242 /* For the same reason (breakpoint conditions), "thread N"
1243 terminates the expression. "thread" could be an identifier, but
1244 an identifier is never followed by a number without intervening
1246 Handle abbreviations of these, similarly to
1247 breakpoint.c:find_condition_and_thread.
1248 TODO: Watch for "goroutine" here? */
1250 && strncmp (tokstart, "thread", namelen) == 0
1251 && (tokstart[namelen] == ' ' || tokstart[namelen] == '\t'))
1253 const char *p = tokstart + namelen + 1;
1255 while (*p == ' ' || *p == '\t')
1257 if (*p >= '0' && *p <= '9')
1261 par_state->lexptr += namelen;
1265 yylval.sval.ptr = tokstart;
1266 yylval.sval.length = namelen;
1268 /* Catch specific keywords. */
1269 std::string copy = copy_name (yylval.sval);
1270 for (const auto &token : ident_tokens)
1271 if (copy == token.oper)
1273 /* It is ok to always set this, even though we don't always
1274 strictly need to. */
1275 yylval.opcode = token.opcode;
1279 if (*tokstart == '$')
1280 return DOLLAR_VARIABLE;
1282 if (pstate->parse_completion && *par_state->lexptr == '\0')
1283 saw_name_at_eof = 1;
1287 /* An object of this type is pushed on a FIFO by the "outer" lexer. */
1288 struct token_and_value
1294 /* A FIFO of tokens that have been read but not yet returned to the
1296 static std::vector<token_and_value> token_fifo;
1298 /* Non-zero if the lexer should return tokens from the FIFO. */
1301 /* Temporary storage for yylex; this holds symbol names as they are
1303 static auto_obstack name_obstack;
1305 /* Build "package.name" in name_obstack.
1306 For convenience of the caller, the name is NUL-terminated,
1307 but the NUL is not included in the recorded length. */
1309 static struct stoken
1310 build_packaged_name (const char *package, int package_len,
1311 const char *name, int name_len)
1313 struct stoken result;
1315 name_obstack.clear ();
1316 obstack_grow (&name_obstack, package, package_len);
1317 obstack_grow_str (&name_obstack, ".");
1318 obstack_grow (&name_obstack, name, name_len);
1319 obstack_grow (&name_obstack, "", 1);
1320 result.ptr = (char *) obstack_base (&name_obstack);
1321 result.length = obstack_object_size (&name_obstack) - 1;
1326 /* Return non-zero if NAME is a package name.
1327 BLOCK is the scope in which to interpret NAME; this can be NULL
1328 to mean the global scope. */
1331 package_name_p (const char *name, const struct block *block)
1334 struct field_of_this_result is_a_field_of_this;
1336 sym = lookup_symbol (name, block, STRUCT_DOMAIN, &is_a_field_of_this).symbol;
1339 && sym->aclass () == LOC_TYPEDEF
1340 && sym->type ()->code () == TYPE_CODE_MODULE)
1346 /* Classify a (potential) function in the "unsafe" package.
1347 We fold these into "keywords" to keep things simple, at least until
1348 something more complex is warranted. */
1351 classify_unsafe_function (struct stoken function_name)
1353 std::string copy = copy_name (function_name);
1355 if (copy == "Sizeof")
1357 yylval.sval = function_name;
1358 return SIZEOF_KEYWORD;
1361 error (_("Unknown function in `unsafe' package: %s"), copy.c_str ());
1364 /* Classify token(s) "name1.name2" where name1 is known to be a package.
1365 The contents of the token are in `yylval'.
1366 Updates yylval and returns the new token type.
1368 The result is one of NAME, NAME_OR_INT, or TYPENAME. */
1371 classify_packaged_name (const struct block *block)
1373 struct block_symbol sym;
1374 struct field_of_this_result is_a_field_of_this;
1376 std::string copy = copy_name (yylval.sval);
1378 sym = lookup_symbol (copy.c_str (), block, VAR_DOMAIN, &is_a_field_of_this);
1382 yylval.ssym.sym = sym;
1383 yylval.ssym.is_a_field_of_this = is_a_field_of_this.type != NULL;
1389 /* Classify a NAME token.
1390 The contents of the token are in `yylval'.
1391 Updates yylval and returns the new token type.
1392 BLOCK is the block in which lookups start; this can be NULL
1393 to mean the global scope.
1395 The result is one of NAME, NAME_OR_INT, or TYPENAME. */
1398 classify_name (struct parser_state *par_state, const struct block *block)
1401 struct block_symbol sym;
1402 struct field_of_this_result is_a_field_of_this;
1404 std::string copy = copy_name (yylval.sval);
1406 /* Try primitive types first so they win over bad/weird debug info. */
1407 type = language_lookup_primitive_type (par_state->language (),
1408 par_state->gdbarch (),
1412 /* NOTE: We take advantage of the fact that yylval coming in was a
1413 NAME, and that struct ttype is a compatible extension of struct
1414 stoken, so yylval.tsym.stoken is already filled in. */
1415 yylval.tsym.type = type;
1419 /* TODO: What about other types? */
1421 sym = lookup_symbol (copy.c_str (), block, VAR_DOMAIN, &is_a_field_of_this);
1425 yylval.ssym.sym = sym;
1426 yylval.ssym.is_a_field_of_this = is_a_field_of_this.type != NULL;
1430 /* If we didn't find a symbol, look again in the current package.
1431 This is to, e.g., make "p global_var" work without having to specify
1432 the package name. We intentionally only looks for objects in the
1436 char *current_package_name = go_block_package_name (block);
1438 if (current_package_name != NULL)
1440 struct stoken sval =
1441 build_packaged_name (current_package_name,
1442 strlen (current_package_name),
1443 copy.c_str (), copy.size ());
1445 xfree (current_package_name);
1446 sym = lookup_symbol (sval.ptr, block, VAR_DOMAIN,
1447 &is_a_field_of_this);
1450 yylval.ssym.stoken = sval;
1451 yylval.ssym.sym = sym;
1452 yylval.ssym.is_a_field_of_this = is_a_field_of_this.type != NULL;
1458 /* Input names that aren't symbols but ARE valid hex numbers, when
1459 the input radix permits them, can be names or numbers depending
1460 on the parse. Note we support radixes > 16 here. */
1461 if ((copy[0] >= 'a' && copy[0] < 'a' + input_radix - 10)
1462 || (copy[0] >= 'A' && copy[0] < 'A' + input_radix - 10))
1464 YYSTYPE newlval; /* Its value is ignored. */
1465 int hextype = parse_number (par_state, copy.c_str (),
1466 yylval.sval.length, 0, &newlval);
1469 yylval.ssym.sym.symbol = NULL;
1470 yylval.ssym.sym.block = NULL;
1471 yylval.ssym.is_a_field_of_this = 0;
1476 yylval.ssym.sym.symbol = NULL;
1477 yylval.ssym.sym.block = NULL;
1478 yylval.ssym.is_a_field_of_this = 0;
1482 /* This is taken from c-exp.y mostly to get something working.
1483 The basic structure has been kept because we may yet need some of it. */
1488 token_and_value current, next;
1490 if (popping && !token_fifo.empty ())
1492 token_and_value tv = token_fifo[0];
1493 token_fifo.erase (token_fifo.begin ());
1495 /* There's no need to fall through to handle package.name
1496 as that can never happen here. In theory. */
1501 current.token = lex_one_token (pstate);
1503 /* TODO: Need a way to force specifying name1 as a package.
1506 if (current.token != NAME)
1507 return current.token;
1509 /* See if we have "name1 . name2". */
1511 current.value = yylval;
1512 next.token = lex_one_token (pstate);
1513 next.value = yylval;
1515 if (next.token == '.')
1517 token_and_value name2;
1519 name2.token = lex_one_token (pstate);
1520 name2.value = yylval;
1522 if (name2.token == NAME)
1524 /* Ok, we have "name1 . name2". */
1525 std::string copy = copy_name (current.value.sval);
1527 if (copy == "unsafe")
1530 return classify_unsafe_function (name2.value.sval);
1533 if (package_name_p (copy.c_str (), pstate->expression_context_block))
1536 yylval.sval = build_packaged_name (current.value.sval.ptr,
1537 current.value.sval.length,
1538 name2.value.sval.ptr,
1539 name2.value.sval.length);
1540 return classify_packaged_name (pstate->expression_context_block);
1544 token_fifo.push_back (next);
1545 token_fifo.push_back (name2);
1548 token_fifo.push_back (next);
1550 /* If we arrive here we don't have a package-qualified name. */
1553 yylval = current.value;
1554 return classify_name (pstate, pstate->expression_context_block);
1557 /* See language.h. */
1560 go_language::parser (struct parser_state *par_state) const
1562 /* Setting up the parser state. */
1563 scoped_restore pstate_restore = make_scoped_restore (&pstate);
1564 gdb_assert (par_state != NULL);
1567 scoped_restore restore_yydebug = make_scoped_restore (&yydebug,
1570 /* Initialize some state used by the lexer. */
1571 last_was_structop = 0;
1572 saw_name_at_eof = 0;
1575 token_fifo.clear ();
1577 name_obstack.clear ();
1579 int result = yyparse ();
1581 pstate->set_operation (pstate->pop ());
1586 yyerror (const char *msg)
1588 if (pstate->prev_lexptr)
1589 pstate->lexptr = pstate->prev_lexptr;
1591 error (_("A %s in expression, near `%s'."), msg, pstate->lexptr);