From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from simark.ca by simark.ca with LMTP id N5k0Msuo/GorAxkAWB0awg (envelope-from ) for ; Tue, 17 Nov 2026 14:19:39 -0500 Authentication-Results: simark.ca; dkim=pass (2048-bit key; secure) header.d=adacore.com header.i=@adacore.com header.a=rsa-sha256 header.s=google header.b=bofb3Fvs; dkim-atps=neutral Received: by simark.ca (Postfix, from userid 112) id AB5DD1E091; Tue, 17 Nov 2026 14:19:39 -0500 (EST) X-Spam-Checker-Version: SpamAssassin 4.0.1 (2024-03-25) on simark.ca X-Spam-Level: X-Spam-Status: No, score=-5.4 required=5.0 tests=ARC_SIGNED,ARC_VALID,BAYES_00, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,MAILING_LIST_MULTI, RCVD_IN_DNSWL_MED autolearn=ham autolearn_force=no version=4.0.1 Received: from vm01.sourceware.org (vm01.sourceware.org [38.145.34.32]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange x25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by simark.ca (Postfix) with ESMTPS id 42F381E023 for ; Tue, 17 Nov 2026 14:19:36 -0500 (EST) Received: from vm01.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 716E44BA2E1F for ; Tue, 17 Nov 2026 19:19:35 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 716E44BA2E1F Authentication-Results: sourceware.org; dkim=pass (2048-bit key, secure) header.d=adacore.com header.i=@adacore.com header.a=rsa-sha256 header.s=google header.b=bofb3Fvs Received: from mail-oi1-x22c.google.com (mail-oi1-x22c.google.com [IPv6:2607:f8b0:4864:20::22c]) by sourceware.org (Postfix) with ESMTPS id C8C484BA2E0A for ; Tue, 17 Nov 2026 19:18:59 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org C8C484BA2E0A Authentication-Results: sourceware.org; dmarc=pass (p=quarantine dis=none) header.from=adacore.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=adacore.com ARC-Filter: OpenARC Filter v1.0.0 sourceware.org C8C484BA2E0A Authentication-Results: sourceware.org; arc=none smtp.remote-ip=2607:f8b0:4864:20::22c ARC-Seal: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1794943140; cv=none; b=O1gR1Ufb0UbfPh98PrmH8HOWwAaQFyPWGVV37iglmKxfMMQUC5bZhzhRTKKFbYe1sbleIJ8rm5crmagieBPupYEdMOnPoMxeFmE4zjXI1dEUuRGrJVimWyadltn6zmJvTmAL1Vnf8imB0aTCwb5WYKHNvrsblA5XcHWT8McLSrU= ARC-Message-Signature: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1794943140; c=relaxed/simple; bh=gz8JCvPjon1ErYvM7QbLMb0kIXlijfwfcx72abrLeTU=; h=DKIM-Signature:From:To:Subject:Date:Message-ID:MIME-Version; b=B9Viwi/2F0xcpFiCLQVNbquaNZ6BDKFgjJ2v959JwFWgGKO2oH9HIrEwcXUzsTKsqguKS9G1ttLFID1f0abzgL43G9UkiRZi62p8aFbdaXvYvaO18/CuVuC5V9c1DTzPs98NVYsGCqflQAtrNAViMxEBuKSrU7p2siltyo0MyN4= ARC-Authentication-Results: i=1; sourceware.org; dkim=pass (2048-bit key, secure) header.d=adacore.com header.i=@adacore.com header.a=rsa-sha256 header.s=google header.b=bofb3Fvs DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org C8C484BA2E0A Received: by mail-oi1-x22c.google.com with SMTP id 5614622812f47-4b190cdc9feso36971b6e.0 for ; Tue, 17 Nov 2026 11:18:59 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=adacore.com; s=google; t=1794943139; x=1795547939; darn=sourceware.org; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:from:to:cc:subject:date:message-id:reply-to:content-type; bh=hVQfNOObeIqWX84s+xW34UEnbmKJFaJ4V49qZZXT+P8=; b=bofb3Fvsrwtuxial/514i6UoXGnY5W+GTEg9Py67o3Y9iAKRfJWXkYDo95Jl8WFJRH o0fysdf66bAxnUkPYNlL76nHiNXbzMvz32w6xAP4VlV87FfqWelOPCYEAfHPU3jP6ndX RlDE1zaxSza80Sce0A/94Z+RXof4uH2tMh9FDN6O8TIwBF+4Lfjd9rHmX2Pn5EfUg6Br nrGWOwNDMrKj5bSz4yExttmkd5qR3AwM3OI2UpHqoU7fuElUy6HYfSRuRePXqbG0AC18 vUh6P/cfevY4Cz0J1S3/cbj8uo78a4N2MZZfZ8kHudqLLZa/HUWI/XFd4iRntd2qvAeX TUkg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1794943139; x=1795547939; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:x-gm-gg:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=hVQfNOObeIqWX84s+xW34UEnbmKJFaJ4V49qZZXT+P8=; b=R9b5v5+s84Ph+T+sOfDqp6rSZK9HflDYI8hMzU9cSuN8ppgIV3zJxw590/m8xJK7wM NZikVBhi0cuBMMs7jgEN0MIe9jjL/IMM1/YJE38n/CZv7Kj92mJNCxFhfXpyQm0mBg6K oSyVsPAPjmb6mcEYdXhQa8rpccUurM+ACrObjIGqez+Syuf1+VB9lI9iovdoVVs6/D8Z HCmS8hI4GXhQGa+5YYq4gLLLTcnIthOX4moVaAkJ/qepcd2aGfx5OR5Yx1CQ5/3GEG+2 bB2IPOlzbpYI4CKwLu3ex8NxQHTAMmykr7AXFuWFr4OI6EQbawLGNmSZQ3Qu4uQkr5K+ wCtw== X-Gm-Message-State: APuU4Z8Y3/tQNjb4evB+esH2Hs7uNBu50qe6a5Z891wq4rJfKA7FrBio JqP/CHmSZ1LLdO1hhsg3ns8xqMA+xF/2vLdNtgKObnPqtJeiv95nSqVtcrod5aPws1pDegD3tr9 1mdgwVQ== X-Gm-Gg: AYBFou0U0HIafG78f5RVX9//zRg0GCvZ+gjq3R9B24ets8YoD6dSk7aBz8p5xAnYG0V ahPiAmHcxN7l0F/n8Ki5GR+8o02HOBXRLUc2pHR5xMCZ24DF1dg71cWLUe6FsTDeCFe9ZAmhnpR LwHMswniAa9+EZ6xd5OCpPW3YGDI+8FW5uinQO2tmVxJTqbVHMdnNoRju5i56cpsonKxzaGlypI wVTsLOkE77fxpU7s6AnYheUzf/MqSSlkp6WgS8FpwWcInDtowds/fa0G5ePPhKaidOdj0DUm4nf tJSsTqIYlbsckB190N+w74Wr3meoW2PPMb96peFTi02zF2cETVMb9XXLdvcx8qHcuELgYvjbVUP /S34x0hXfG81IoBM8rNAymJ0LzF+aN9EwOzTv/Mv4LzOZRFYcZVh51Ui0SNa6gDRfkmwzdioRMV vr8J8nB7MdOWUkwHmOrph6bn7OW0v+4udmU0+NW465lhFsgZ4stheyfW68ikTn3peAudE0S4ee4 POYZCOR1zvkAWOiqnEmNFoKVIgxoe2wK8T+yeG5Ls0C6muUlLgGHP99HEOFIitHJOL8WF/tqy3g J4BMob7qzo7K2JDzmOGS6aAcvhCIasYfxLYos2r5c5N9nbTAJwJ5k0X3nMxPjBqglMLqk3yWwQ= = X-Received: by 2002:a05:6808:178b:b0:571:d57e:cd78 with SMTP id 5614622812f47-5773ea4f19fmr790334b6e.8.1794943138474; Tue, 17 Nov 2026 11:18:58 -0800 (PST) Received: from bapiya (97-122-110-129.hlrn.qwest.net. [97.122.110.129]) by smtp.gmail.com with ESMTPSA id 586e51a60fabf-4b744120eaesm139729fac.7.2026.11.17.11.18.57 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 17 Nov 2026 11:18:58 -0800 (PST) From: Tom Tromey To: gdb-patches@sourceware.org Cc: Tom Tromey Subject: [PATCH v2] Rewrite the Ada lexer Date: Tue, 17 Nov 2026 12:18:54 -0700 Message-ID: <20261117191854.2893194-1-tromey@adacore.com> X-Mailer: git-send-email 2.56.0 MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-BeenThere: gdb-patches@sourceware.org X-Mailman-Version: 2.1.30 Precedence: list List-Id: Gdb-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: gdb-patches-bounces~public-inbox=simark.ca@sourceware.org Recently a series landed that changed how the Ada lexer was built. In particular, commit d3d68d79 ("gdb: let the parser and lexer generators prefix their symbols") changed gdb to require a newer version of flex. Unfortunately, this version of flex is reported as being difficult to build with mingw; and this change broke all the Windows-hosted builds at AdaCore. Rather than try to puzzle out the flex build, I decided to rewrite the lexer to avoid the flex dependency. This patch is the result. I tried for a fairly minimal transition, so some oddities are preserved. Further cleanups are possible (I have a few I will send later). I've also added some unit tests. In some cases these test things that previously were not tested in the tree. v2: addressed review comments. Regression tested on x86-64 Fedora 43. --- gdb/Makefile.in | 30 +- gdb/ada-exp-parser.c | 975 +++++++++++++++++++++++++++++++++++++++---- gdb/ada-exp-parser.h | 151 ++++--- gdb/ada-exp-parser.y | 11 +- gdb/ada-lex.l | 346 --------------- 5 files changed, 993 insertions(+), 520 deletions(-) delete mode 100644 gdb/ada-lex.l diff --git a/gdb/Makefile.in b/gdb/Makefile.in index 55c4d012f25..7bf30086199 100644 --- a/gdb/Makefile.in +++ b/gdb/Makefile.in @@ -128,11 +128,6 @@ COMPILE = $(ECHO_CXX) $(COMPILE.pre) $(INTERNAL_CFLAGS) $(CXXFLAGS) \ YACC = @YACC@ -# This is used to rebuild ada-lex-gen.c from ada-lex.l. If the program -# is not defined, but ada-lex-gen.c is present, compilation will continue, -# possibly with a warning. -FLEX = flex - YLWRAP = $(srcdir)/../ylwrap # where to find makeinfo, preferably one designed for texinfo-2 @@ -2128,7 +2123,6 @@ REQUIRED_SUBDIRS = doc | testsuite | data-directory # Parser intermediate files. YYFILES = \ ada-exp-parser-gen.c \ - ada-lex-gen.c \ c-exp-parser-gen.c \ cp-name-parser-gen.c \ d-exp-parser-gen.c \ @@ -2137,11 +2131,9 @@ YYFILES = \ m2-exp-parser-gen.c \ p-exp-parser-gen.c -# ada-lex-gen.c is included by another file, so it shouldn't wind up as -# a .o itself. -YYOBJ = $(filter-out ada-lex-gen.o,$(patsubst %.c,%.o,$(YYFILES))) +YYOBJ = $(patsubst %.c,%.o,$(YYFILES)) -# The headers bison/byacc and flex generate alongside the files above. +# The headers bison/byacc generate alongside the files above. YYHFILES = $(patsubst %-gen.c,%-gen.h,$(YYFILES)) # Files that used to be generated in the build directory (for builds from git @@ -2160,7 +2152,6 @@ DISTSTUFF = $(YYFILES) $(YYHFILES) # All generated files which can be included by another file. generated_files = \ - ada-lex-gen.c \ config.h \ jit-reader.h \ $(YYHFILES) \ @@ -2783,7 +2774,7 @@ po/$(PACKAGE).pot: force # -# YACC/LEX dependencies +# YACC dependencies # # LANG-exp-parser-gen.c is generated in objdir from LANG-exp-parser.y if # it doesn't exist in srcdir, then compiled in objdir to @@ -2794,23 +2785,21 @@ po/$(PACKAGE).pot: force # Strictly speaking c-exp-parser-gen.c should therefore depend on # Makefile.in, but that was a pretty big annoyance. -# Cancel make's built-in rules for producing a .c file from a .y or .l +# Cancel make's built-in rules for producing a .c file from a .y # file, to avoid them producing a /foo-exp.c file from # /foo-exp.y, when we also have a hand-written /foo-exp.c # file. %.c: %.y -%.c: %.l # Post-process a file produced by a parser generator, see the script # for details. POST_PROCESS_PARSER_OUTPUT_SH = $(srcdir)/post-process-parser-output.sh POST_PROCESS_PARSER_OUTPUT = $(SHELL) $(POST_PROCESS_PARSER_OUTPUT_SH) -# The prefix to give to the symbols each parser or lexer generator +# The prefix to give to the symbols each parser generator # produces, so that they can coexist in the same program. There is no # rule tying it to the file name, so spell it out for each one. YY_PREFIX_ada-exp-parser = ada_yy -YY_PREFIX_ada-lex = ada_yy YY_PREFIX_c-exp-parser = c_yy YY_PREFIX_cp-name-parser = cpname_yy YY_PREFIX_d-exp-parser = d_yy @@ -2830,15 +2819,6 @@ YY_PREFIX_p-exp-parser = pascal_yy @$(POST_PROCESS_PARSER_OUTPUT) bison $* < $*-gen.h.tmp > $*-gen.h.new \ && rm -f $*-gen.h.tmp && mv $*-gen.h.new $*-gen.h -%-gen.c %-gen.h: %.l $(POST_PROCESS_PARSER_OUTPUT_SH) - $(ECHO_LEX) $(FLEX) -t -P $(YY_PREFIX_$*) \ - --header-file=$*-gen.h.tmp $< > $*-gen.c.tmp \ - || (rm -f $*-gen.c.tmp $*-gen.h.tmp; false) - @$(POST_PROCESS_PARSER_OUTPUT) flex $* < $*-gen.c.tmp > $*-gen.c.new \ - && rm -f $*-gen.c.tmp && mv $*-gen.c.new $*-gen.c - @$(POST_PROCESS_PARSER_OUTPUT) flex $* < $*-gen.h.tmp > $*-gen.h.new \ - && rm -f $*-gen.h.tmp && mv $*-gen.h.new $*-gen.h - # XML rules xml-builtin.c: stamp-xml; @true diff --git a/gdb/ada-exp-parser.c b/gdb/ada-exp-parser.c index 53f5a709caf..f82731623c2 100644 --- a/gdb/ada-exp-parser.c +++ b/gdb/ada-exp-parser.c @@ -20,11 +20,12 @@ #include "ada-exp-parser.h" #include "ada-exp-parser-gen.h" #include "ada-lang.h" -#include "ada-lex-gen.h" #include "block.h" #include "cli/cli-style.h" #include "gdbsupport/scoped_restore.h" +#include "gdbsupport/selftest.h" #include "parser-defs.h" +#include "inferior.h" using namespace expr; @@ -38,9 +39,75 @@ int ada_yyparse (); extern int ada_yydebug; +/* A regular expression matching Ada numbers. */ + +static const char number_regex_text[] = + /* We have to match the first character. */ + "^" + + /* Hex number. */ + "(0x[0-9a-f][0-9a-f]*)" +#define HEX_NUMBER 1 + "|" + + /* Floating point number with positive exponent. */ + "([0-9][0-9_]*e[+]?[0-9][0-9_]*)" +#define FLOAT_POSEXP 2 + "|" + + /* Floating point number with optional exponent. */ + "([0-9][0-9_]*\\.[0-9][0-9_]*(e[+-][0-9][0-9_]*)?)" +#define FLOAT_OPTEXP 3 + "|" + + /* Floating point numbers but in another base. The "llf" is a gdb + extension, see lex_number. The regexp is a little funny so that + it can match only 0, 1, or 2 "l"s. */ + "([0-9][0-9_]*(l?l?f)?#[0-9a-f][0-9a-f_]*#(e[+]?[0-9][0-9_]*)?)" +#define FLOAT_EXTENSION 5 +#define EXPONENT 7 + "|" + + /* Based real literals. */ + "([0-9][0-9_]*#[0-9a-f][0-9a-f_]*\\.[0-9a-f][0-9a-f_]*#(e[+-][0-9][0-9_]*)?)" +#define BASED_REAL 8 + "|" + + /* Lowly integers. */ + "[0-9][0-9_]*"; + +/* The number of subexpressions to allocate space for, including the + "0th" whole match subexpression. */ +#define NUM_SUBEXPRESSIONS 10 + +/* The compiled number-matching regex. */ + +static regex_t number_regex; + +/* A regular expression matching an Ada operator, surrounded by + quotes. */ + +static const char operator_regex_text[] = + "^\"(<=|>=|\\*\\*|/=|and|or|xor|not|mod|rem|abs|[-+*/=<>&])\""; + +/* The number of subexpressions to allocate space for, including the + "0th" whole match subexpression. */ +#define NUM_OPER_SUBEXPRESSIONS 2 + +/* The compiled operator-matching regex. */ + +static regex_t operator_regex; + namespace ada_exp_parser { +/* Map a string to a code. */ +struct code_entry +{ + const char *name; + int code; +}; + /* See ada-exp-parser.h. */ struct parser_state *pstate; @@ -49,12 +116,13 @@ struct parser_state *pstate; struct ada_parse_state *ada_parser; -/* See ada-exp-parser.h. */ +/* Copy S2 to S1, removing all underscores, and downcasing all + letters. Stops at END. */ -void -canonicalizeNumeral (char *s1, const char *s2) +static void +canonicalize_numeral (char *s1, const char *s2, const char *end) { - for (; *s2 != '\000'; s2 += 1) + for (; s2 != end; s2 += 1) { if (*s2 != '_') { @@ -207,51 +275,47 @@ processReal (struct parser_state *par_state, const char *num0) /* See ada-exp-parser.h. */ struct stoken -processId (const char *name0, int len) +ada_parse_state::process_id (std::string_view name0) { - char *name = (char *) obstack_alloc (&ada_parser->temp_space, len + 11); - int i0, i; + char *name = (char *) obstack_alloc (&ada_parser->temp_space, + name0.size () + 11); struct stoken result; result.ptr = name; - while (len > 0 && c_isspace (name0[len-1])) - len -= 1; + while (!name0.empty () && c_isspace (name0.back ())) + name0 = name0.substr (0, name0.size () - 1); - if (name0[0] == '<' || strstr (name0, "___") != NULL) + if (!name0.empty () + && (name0[0] == '<' || name0.find ("___") != std::string_view::npos)) { - strncpy (name, name0, len); + size_t len = name0.size (); + strncpy (name, name0.data (), len); name[len] = '\000'; result.length = len; return result; } bool in_quotes = false; - i = i0 = 0; - while (i0 < len) + int i = 0; + for (char c : name0) { - if (name0[i0] == COMPLETE_CHAR) - { - /* Just ignore. */ - ++i0; - } - else if (in_quotes) - name[i++] = name0[i0++]; - else if (c_isalnum (name0[i0])) + if (in_quotes) + name[i++] = c; + else if (c_isalnum (c)) + name[i++] = c_tolower (c); + else if (c_isspace (c)) { - name[i] = c_tolower (name0[i0]); - i += 1; i0 += 1; + /* Nothing. */ } - else if (c_isspace (name0[i0])) - i0 += 1; - else if (name0[i0] == '\'') + else if (c == '\'') { /* Copy the starting quote, but not the ending quote. */ if (!in_quotes) - name[i++] = name0[i0++]; + name[i++] = c; in_quotes = !in_quotes; } else - name[i++] = name0[i0++]; + name[i++] = c; } name[i] = '\000'; @@ -300,29 +364,6 @@ processString (const char *text, int len) return result; } -/* See ada-exp-parser.h. */ - -int -find_dot_all (const char *str) -{ - int i; - - for (i = 0; str[i] != '\000'; i++) - if (str[i] == '.') - { - int i0 = i; - - do - i += 1; - while (c_isspace (str[i])); - - if (strncasecmp (str + i, "all", 3) == 0 - && !c_isalnum (str[i + 3]) && str[i + 3] != '_') - return i0; - } - return -1; -} - /* Returns non-zero iff string SUBSEQ matches a subsequence of STR, ignoring case. */ @@ -340,8 +381,8 @@ subseqMatch (const char *subseq, const char *str) } -static const struct { const char *name; int code; } -attributes[] = { +static const struct code_entry attributes[] = +{ { "address", TICK_ADDRESS }, { "unchecked_access", TICK_ACCESS }, { "unrestricted_access", TICK_ACCESS }, @@ -365,39 +406,32 @@ attributes[] = { /* See ada-exp-parser.h. */ int -processAttribute (const char *str) +ada_parse_state::process_attribute (const std::string &str, bool completing) { - gdb_assert (*str == '\''); - ++str; - while (c_isspace (*str)) - ++str; - - int len = strlen (str); - if (len > 0 && str[len - 1] == COMPLETE_CHAR) + size_t len = str.length (); + if (completing) { - /* This is enforced by YY_INPUT. */ - gdb_assert (pstate->parse_completion); ada_yylval.sval.ptr = obstack_strndup (&ada_parser->temp_space, - str, len - 1); - ada_yylval.sval.length = len - 1; + str.c_str (), len); + ada_yylval.sval.length = len; return TICK_COMPLETE; } for (const auto &item : attributes) - if (strcasecmp (str, item.name) == 0) + if (strcasecmp (str.c_str (), item.name) == 0) return item.code; std::optional found; for (const auto &item : attributes) - if (subseqMatch (str, item.name)) + if (subseqMatch (str.c_str (), item.name)) { if (!found.has_value ()) found = item.code; else - error (_("ambiguous attribute name: \"%s\""), str); + error (_("ambiguous attribute name: \"%s\""), str.c_str ()); } if (!found.has_value ()) - error (_("unrecognized attribute: \"%s\""), str); + error (_("unrecognized attribute: \"%s\""), str.c_str ()); return *found; } @@ -416,17 +450,788 @@ ada_tick_completer::complete (struct expression *exp, return true; } -/* See ada-exp-parser.h. */ +int +ada_parse_state::lex_number () +{ + const char *num_start = pstate->lexptr; + gdb_assert (c_isdigit (*num_start)); + + regmatch_t subexps[NUM_SUBEXPRESSIONS]; + int match = regexec (&number_regex, num_start, ARRAY_SIZE (subexps), + subexps, 0); + /* Failure means the regexp is broken. */ + gdb_assert (match == 0); + + pstate->lexptr += subexps[0].rm_eo; + +#define NUMERAL_WIDTH 256 + char numbuf[NUMERAL_WIDTH]; + if (subexps[HEX_NUMBER].rm_so != -1) + { + canonicalize_numeral (numbuf, num_start + 2, pstate->lexptr); + return processInt (pstate, "16#", numbuf, nullptr); + } + else if (subexps[FLOAT_POSEXP].rm_so != -1) + { + canonicalize_numeral (numbuf, num_start, pstate->lexptr); + char *e_ptr = strrchr (numbuf, 'e'); + *e_ptr = '\0'; + return processInt (pstate, nullptr, numbuf, e_ptr + 1); + } + else if (subexps[FLOAT_OPTEXP].rm_so != -1) + { + canonicalize_numeral (numbuf, num_start, pstate->lexptr); + return processReal (pstate, numbuf); + } + else if (subexps[FLOAT_EXTENSION].rm_so != -1) + { + canonicalize_numeral (numbuf, num_start, pstate->lexptr); + char *e_ptr = nullptr; + if (subexps[EXPONENT].rm_so != -1) + { + /* We can't use the 'rm_so' here because + canonicalize_numeral might have removed some underscores. + But we know the 'e' appears after the '#' so we can + search for it and not get one of the (possibly hex) + numerals. */ + e_ptr = strrchr (numbuf, 'e'); + gdb_assert (e_ptr != nullptr); + *e_ptr = '\0'; + ++e_ptr; + } + return processInt (pstate, numbuf, strchr (numbuf, '#') + 1, e_ptr); + } + else if (subexps[BASED_REAL].rm_so != -1) + error (_("Based real literals not implemented yet.")); + + /* Must be a simple integer. */ + canonicalize_numeral (numbuf, num_start, pstate->lexptr); + return processInt (pstate, nullptr, numbuf, nullptr); +} + +static const code_entry keywords[] = +{ + { "abs", ABS }, + { "and", _AND_ }, + { "delta", DELTA }, + { "else", ELSE }, + { "for", FOR }, + { "in", IN }, + { "mod", MOD }, + { "new", NEW }, + { "not", NOT }, + { "null", NULL_PTR }, + { "or", OR }, + { "others", OTHERS }, + { "rem", REM }, + { "then", THEN }, + { "with", WITH }, + { "xor", XOR }, + /* True and False are not keywords in Ada, but rather enumeration + constants. However, the boolean type is no longer represented as + an enum, so True and False are no longer defined in symbol + tables. We compromise by making them keywords (when bare). */ + { "true", TRUEKEYWORD }, + { "false", FALSEKEYWORD }, + { "if", 0 }, + { "task", 0 }, + { "thread", -1 }, +}; + +bool +ada_parse_state::check_thread_keyword (const char *text) +{ + /* "thread" has to be followed by whitespace and then a digit in + order to be treated as a keyword. */ + if (!c_isspace (*text)) + return false; + const char *after = skip_spaces (text); + return c_isdigit (*after); +} + +std::optional +ada_parse_state::check_keyword (size_t len) +{ + const char *start = pstate->lexptr; + for (const code_entry &entry : keywords) + { + if (strlen (entry.name) == len + && strncasecmp (entry.name, start, len) == 0) + { + int result = entry.code; + if (result == -1) + { + /* Special handling for the "thread" keyword. */ + if (!check_thread_keyword (pstate->lexptr + len)) + continue; + result = 0; + } + return result; + } + } + + return std::nullopt; +} + +const char * +ada_parse_state::lex_operator (const char *start) +{ + gdb_assert (*start == '"'); + regmatch_t subexps[NUM_SUBEXPRESSIONS]; + int match = regexec (&operator_regex, start, ARRAY_SIZE (subexps), + subexps, 0); + if (match != 0) + return nullptr; + return start + subexps[0].rm_eo; +} + +int +ada_parse_state::lex_identifier (const char *id_end) +{ + bool is_quoted = *pstate->lexptr == '<'; + bool completing = *id_end == '\0' && pstate->parse_completion; + + /* Only check keywords when the identifier is unquoted, and when not + completing. */ + if (!is_quoted && !completing) + { + std::optional result = check_keyword (id_end - pstate->lexptr); + if (result.has_value ()) + { + /* If the keyword results in an EOF, leave the parser's + lexptr pointing at the start of the keyword. Otherwise, + update to the end. */ + if (*result != 0) + pstate->lexptr = id_end; + return *result; + } + } + + while (true) + { + const char *iter = skip_spaces (id_end); + if (*iter != '.') + break; + iter = skip_spaces (iter + 1); + + const char *new_id_end = nullptr; + if (*iter == '"') + new_id_end = lex_operator (iter); + else if (c_isalpha (*iter) || *iter == '_' || *iter == '<') + new_id_end = lex_simple_identifier (iter); + if (new_id_end == nullptr) + break; + + /* Skip ".all" and leave it for a later DOT_ID lex. */ + if (new_id_end - iter == 3 && strncasecmp (iter, "all", 3) == 0) + break; + + id_end = new_id_end; + completing = *id_end == '\0' && pstate->parse_completion; + } + + ada_yylval.sval = process_id ({ pstate->lexptr, + (size_t) (id_end - pstate->lexptr) }); + + id_end = skip_spaces (id_end); + if (*id_end == '\'') + m_before_qual_quote = true; + + pstate->lexptr = id_end; + return completing ? NAME_COMPLETE : NAME; +} void -rewind_to_char (int ch) +ada_parse_state::invalid_char () { - pstate->lexptr -= ada_yyleng; - while (c_toupper (*pstate->lexptr) != c_toupper (ch)) - pstate->lexptr -= 1; - ada_yyrestart (NULL); + error (_("Invalid character '%s' in expression."), pstate->lexptr); } +const char * +ada_parse_state::lex_simple_identifier (const char *text) +{ + gdb_assert (c_isalpha (*text) || *text == '_' || *text == '<'); + + const char *iter = text; + bool quoted = (*iter == '<'); + if (quoted) + { + ++iter; + if (!c_isalpha (*iter) && *iter != '_') + return nullptr; + ++iter; + } + + auto as_unsigned = [] (const char *ptr) + { + return *(const unsigned char *) ptr; + }; + + while (c_isalnum (*iter) || *iter == '_' + || (!quoted && as_unsigned (iter) >= 0x80 + && as_unsigned (iter) <= 0xff)) + ++iter; + + if (quoted) + { + /* A quirk of the flex lexer was that completion didn't work for + Ada-quoted symbols like . Perhaps TAB + somewhere before the '>' ought to work. */ + if (*iter != '>') + return nullptr; + ++iter; + } + + return iter; +} + +int +ada_parse_state::lex_dot () +{ + gdb_assert (*pstate->lexptr == '.'); + const char *save = pstate->lexptr; + pstate->lexptr = skip_spaces (pstate->lexptr + 1); + + int name_token = 0; + if (*pstate->lexptr == '<' || *pstate->lexptr == '_' + || c_isalpha (*pstate->lexptr)) + { + const char *id_end = lex_simple_identifier (pstate->lexptr); + if (id_end != nullptr) + { + pstate->lexptr = id_end; + name_token = NAME; + } + } + + if (*pstate->lexptr == '\0' && pstate->parse_completion) + name_token = NAME_COMPLETE; + + if (name_token != NAME && name_token != NAME_COMPLETE) + { + pstate->lexptr = save; + invalid_char (); + } + + ada_yylval.sval = process_id ({ save + 1, + (size_t) (pstate->lexptr - save - 1) }); + return name_token == NAME_COMPLETE ? DOT_COMPLETE : DOT_ID; +} + +const char * +ada_parse_state::recognize_encoded_char (const char *bracket) +{ + if (bracket[0] == '[' && bracket[1] == '"') + { + const char *start = bracket + 2; + const char *iter = start; + + /* Handle the weird case of ["""], which just means a double + quote. */ + if (*iter == '"') + ++iter; + else + { + while (c_isxdigit (*iter)) + ++iter; + if (iter - start < 2) + return nullptr; + } + + if (iter[0] == '"' && iter[1] == ']') + { + /* Ada-style quoted character. */ + return iter + 2; + } + } + return nullptr; +} + +int +ada_parse_state::lex_single_quote () +{ + gdb_assert (*pstate->lexptr == '\''); + + bool before_qual_quote = m_before_qual_quote; + m_before_qual_quote = false; + + if (!before_qual_quote) + { + /* Look for the GDB block extension "'STUFF'::". */ + const char *block_iter = pstate->lexptr + 1; + while (*block_iter != '\0' && *block_iter != '\'') + ++block_iter; + /* Require a non-empty block. */ + if (block_iter[0] == '\'' && block_iter - pstate->lexptr - 1 > 0) + { + const char *block_end = skip_spaces (block_iter + 1); + if (block_end[0] == ':' && block_end[1] == ':') + { + ada_yylval.sval + = process_id ({ pstate->lexptr, + (size_t) (block_end - pstate->lexptr) }); + /* Leave the "::" to be lexed later. */ + pstate->lexptr = block_end; + return NAME; + } + } + + if (c_isprint (pstate->lexptr[1]) && pstate->lexptr[2] == '\'') + { + /* Ordinary character literal. */ + int the_char = pstate->lexptr[1]; + ada_yylval.typed_char.val = the_char; + ada_yylval.typed_char.type = type_for_char (pstate, the_char); + pstate->lexptr += 3; + return CHARLIT; + } + + const char *end_bracket = recognize_encoded_char (pstate->lexptr + 1); + if (end_bracket != nullptr) + { + if (*end_bracket != '\'') + { + /* We saw something pretty odd. */ + error (_("Unterminated character literal")); + } + /* The character starts at an offset from the initial single + quote. */ + ULONGEST v = strtoulst (pstate->lexptr + 3, nullptr, 16); + ada_yylval.typed_char.val = v; + ada_yylval.typed_char.type = type_for_char (pstate, v); + pstate->lexptr = end_bracket + 1; + return CHARLIT; + } + } + + /* Handle 'ATTRIBUTE; with a special case when completing just after + a single quote. */ + const char *attr_start = skip_spaces (pstate->lexptr + 1); + if (c_isalpha (*attr_start) + || (pstate->parse_completion && *attr_start == '\0')) + { + const char *iter = attr_start; + while (*iter == '_' || c_isalpha (*iter)) + ++iter; + bool completing = pstate->parse_completion && *iter == '\0'; + pstate->lexptr = iter; + return process_attribute (std::string (attr_start, iter - attr_start), + completing); + } + + ++pstate->lexptr; + return '\''; +} + +int +ada_parse_state::lex_double_quote () +{ + gdb_assert (*pstate->lexptr == '"'); + const char *start = pstate->lexptr + 1; + + const char *iter = start; + while (*iter != '"' && *iter != '\0') + { + /* Note that we don't handle bracket sequences of more than 2 + digits here. Currently there's no support for wide or + wide-wide strings. */ + const char *end_bracket = recognize_encoded_char (iter); + if (end_bracket != nullptr) + iter = end_bracket; + else if (c_isprint (*iter)) + ++iter; + else + break; + } + + if (*iter != '"') + error (_("ill-formed or non-terminated string literal")); + + ada_yylval.sval = processString (start, iter - start); + pstate->lexptr = iter + 1; + return STRING; +} + +int +ada_parse_state::lex_dollar () +{ + gdb_assert (*pstate->lexptr == '$'); + const char *start = pstate->lexptr++; + while (c_isalnum (*pstate->lexptr) || *pstate->lexptr == '_' + || *pstate->lexptr == '$') + ++pstate->lexptr; + ada_yylval.sval.ptr = start; + ada_yylval.sval.length = pstate->lexptr - start; + return DOLLAR_VARIABLE; +} + +static const code_entry punct[] = +{ + { "=>", ARROW }, + { "..", DOTDOT }, + { "**", STARSTAR }, + { ":=", ASSIGN }, + { "/=", NOTEQUAL }, + { "<=", LEQ }, + { ">=", GEQ }, + { "::", COLONCOLON }, + /* "--" is documented in the manual as being a comment. */ + { "--", 0 }, +}; + +int +ada_parse_state::lex () +{ + /* If m_before_qual_quote is set, we must be examining a single + quote. */ + gdb_assert (!m_before_qual_quote || *pstate->lexptr == '\''); + + pstate->lexptr = skip_spaces (pstate->lexptr); + + if (pstate->lexptr[0] != '\0' && pstate->lexptr[1] != '\0') + for (const code_entry &entry : punct) + { + size_t len = strlen (entry.name); + gdb_assert (len == 2); + if (strncmp (entry.name, pstate->lexptr, len) == 0) + { + /* Handle the "--" comment case specially. */ + if (entry.code == 0) + { + size_t rest = strlen (pstate->lexptr); + pstate->lexptr += rest; + } + else + pstate->lexptr += len; + return entry.code; + } + } + + switch (*pstate->lexptr) + { + case '\0': + return 0; + + case '-': + case '=': + case '*': + case ':': + case '&': + case '+': + case '{': + case '}': + case '@': + case '/': + case '>': + case '|': + case ';': + case '[': + case ']': + return *pstate->lexptr++; + + case ',': + if (m_paren_depth == 0 && pstate->comma_terminates) + return 0; + else + return *pstate->lexptr++; + + case '(': + ++m_paren_depth; + return *pstate->lexptr++; + + case ')': + if (m_paren_depth == 0) + return 0; + --m_paren_depth; + return *pstate->lexptr++; + + case '\'': + return lex_single_quote (); + + case '"': + return lex_double_quote (); + + case '$': + return lex_dollar (); + + case '.': + return lex_dot (); + } + + if (c_isalpha (*pstate->lexptr) || *pstate->lexptr == '_' + || *pstate->lexptr == '<') + { + const char *id_end = lex_simple_identifier (pstate->lexptr); + if (id_end == nullptr) + { + /* It shouldn't be possible to reach here when starting with + a letter or underscore. */ + gdb_assert (*pstate->lexptr == '<'); + return *pstate->lexptr++; + } + return lex_identifier (id_end); + } + + if (c_isdigit (*pstate->lexptr)) + return lex_number (); + + invalid_char (); +} + +#if GDB_SELF_TEST + +namespace selftests +{ + +/* Helper that checks that a given lex causes an exception. */ +static void +ada_lex_test_error (const char *input) +{ + /* We need a dummy parser. */ + parser_state ps (language_def (language_ada), current_inferior ()->arch (), + nullptr, 0, 0, input, false, nullptr); + scoped_restore save_parser = make_scoped_restore (&pstate, &ps); + + ada_parse_state ada_ps (input); + /* This is probably not needed, but also it doesn't hurt. */ + scoped_restore save_aps = make_scoped_restore (&ada_parser, &ada_ps); + + bool saw_failure = false; + try + { + ada_ps.lex (); + } + catch (const gdb_exception_error &err) + { + saw_failure = true; + } + SELF_CHECK (saw_failure); +} + +/* Helper to check a lexing sequence, also checking string values of + tokens. */ +static void +ada_lex_test_sequence (const char *input, + gdb::array_view expected, + bool completion = false) +{ + /* We need a dummy parser. */ + parser_state ps (language_def (language_ada), current_inferior ()->arch (), + nullptr, 0, 0, input, completion, nullptr); + scoped_restore save_parser = make_scoped_restore (&pstate, &ps); + + ada_parse_state ada_ps (input); + /* This is probably not needed, but also it doesn't hurt. */ + scoped_restore save_aps = make_scoped_restore (&ada_parser, &ada_ps); + for (const code_entry &entry : expected) + { + int token = ada_ps.lex (); + SELF_CHECK (token == entry.code); + + bool has_string_value = (token == NAME || token == NAME_COMPLETE + || token == DOT_ID || token == DOT_COMPLETE + || token == STRING + || token == DOLLAR_VARIABLE + || token == TICK_COMPLETE); + if (has_string_value) + { + std::string_view contents (ada_yylval.sval.ptr, + ada_yylval.sval.length); + SELF_CHECK (contents == entry.name); + } + else + SELF_CHECK (entry.name == nullptr); + } + + /* Test that all the input was used. */ + SELF_CHECK (*ps.lexptr == '\0'); +} + +/* Helper that checks an integer value. */ +static void +ada_lex_test_integer (const char *input, int value) +{ + /* We need a dummy parser. */ + parser_state ps (language_def (language_ada), current_inferior ()->arch (), + nullptr, 0, 0, input, false, nullptr); + scoped_restore save_parser = make_scoped_restore (&pstate, &ps); + + ada_parse_state ada_ps (input); + /* This is probably not needed, but also it doesn't hurt. */ + scoped_restore save_aps = make_scoped_restore (&ada_parser, &ada_ps); + + int token = ada_ps.lex (); + SELF_CHECK (token == INT); + SELF_CHECK (*ada_yylval.typed_val.val == value); +} + +static void +ada_lex_tests () +{ + const code_entry cc_test[] = + { + { "blockname", NAME }, + { nullptr, COLONCOLON }, + { "duck", NAME }, + { nullptr, 0 } + }; + ada_lex_test_sequence ("blockname::duck", cc_test); + + const code_entry ccq_test[] = + { + { "'blockname'", NAME }, + { nullptr, COLONCOLON }, + { "duck", NAME }, + { nullptr, 0 } + }; + ada_lex_test_sequence ("'blockname'::duck", ccq_test); + ada_lex_test_sequence ("'blockname' :: duck", ccq_test); + + /* This should not lex as a character literal. */ + const code_entry ccq2_test[] = + { + { "'a'", NAME }, + { nullptr, COLONCOLON }, + { "duck", NAME }, + { nullptr, 0 } + }; + ada_lex_test_sequence ("'a'::duck", ccq2_test); + + const code_entry comment_test[] = + { + { "variable", NAME }, + { nullptr, 0 } + }; + ada_lex_test_sequence ("variable -- comment text here", comment_test); + + const code_entry oper_test[] = + { + { "name.\"mod\"", NAME }, + { nullptr, 0 } + }; + ada_lex_test_sequence (" name . \"MoD\" ", oper_test); + + const code_entry quote_test[] = + { + { ".whatever", NAME }, + { "all", DOT_ID }, + { "rest", DOT_ID }, + { nullptr, 0 } + }; + ada_lex_test_sequence (".whatever.all.rest", quote_test); + + const code_entry uquote_test[] = + { + { "<__leading_uscore>", NAME }, + { nullptr, 0 } + }; + ada_lex_test_sequence ("<__leading_uscore>", uquote_test); + + const code_entry qual_test[] = + { + { "char_enum", NAME }, + { nullptr, '\'' }, + { nullptr, '(' }, + { nullptr, CHARLIT }, + { nullptr, ')' }, + { nullptr, 0 } + }; + ada_lex_test_sequence (" Char_Enum ' ( 'B' ) ", qual_test); + + /* This failed historically since the TAB character is not + "printable". */ + ada_lex_test_error ("\"\t\""); + + /* This should fail due to unbalanced quotes. */ + ada_lex_test_error ("'[\"61\"]x"); + + const code_entry char_test[] = + { + { nullptr, CHARLIT }, + { nullptr, 0 } + }; + ada_lex_test_sequence ("'[\"61\"]'", char_test); + ada_lex_test_sequence ("'\"'", char_test); + ada_lex_test_sequence ("' '", char_test); + + const code_entry str_test[] = + { + { "a string \"", STRING }, + { nullptr, 0 } + }; + ada_lex_test_sequence ("\"[\"61\"] string [\"\"\"]\"", str_test); + + const code_entry compl_test[] = + { + { "duck.duck", NAME }, + { "goose", TICK_COMPLETE }, + { nullptr, 0 } + }; + ada_lex_test_sequence ("duck.duck'goose", compl_test, true); + + const code_entry compl2_test[] = + { + { "pck.inner", NAME }, + { "", DOT_COMPLETE }, + { nullptr, 0 } + }; + ada_lex_test_sequence ("pck.inner.", compl2_test, true); + + const code_entry compl3_test[] = + { + { nullptr, '(' }, + { "name", NAME }, + { nullptr, ')' }, + { "", DOT_COMPLETE }, + { nullptr, 0 } + }; + ada_lex_test_sequence ("(name).", compl3_test, true); + + const code_entry compl4_test[] = + { + { nullptr, '(' }, + { "name", NAME }, + { nullptr, ')' }, + { "fl", DOT_COMPLETE }, + { nullptr, 0 } + }; + ada_lex_test_sequence ("(name).fl", compl4_test, true); + + const code_entry tick_test[] = + { + { "duck.duck", NAME }, + { nullptr, TICK_MIN }, + { nullptr, 0 } + }; + ada_lex_test_sequence ("duck.duck ' min", tick_test); + + const code_entry us3_test[] = + { + { "x", NAME }, + { nullptr, '+' }, + { "a___b", NAME }, + { nullptr, 0 } + }; + ada_lex_test_sequence ("X + a___b", us3_test); + + ada_lex_test_integer ("0xff", 255); + ada_lex_test_integer ("0xffff", 65535); + ada_lex_test_integer ("019", 19); + ada_lex_test_integer ("0", 0); + ada_lex_test_integer ("16#ff#", 255); + ada_lex_test_integer ("16#ee#", 238); + ada_lex_test_integer ("16#EE#", 238); + ada_lex_test_integer ("8#77#", 63); + + /* Based reals aren't handled. */ + ada_lex_test_error ("16#abcd.ef01#"); + ada_lex_test_error ("16#abcd.ef01#e+23"); +} + +} /* namespace selftests */ + +#endif /* GDB_SELF_TEST */ + /* See ada-exp-parser.h. */ operation_up @@ -1337,8 +2142,6 @@ ada_parse (struct parser_state *par_state) scoped_restore restore_yydebug = make_scoped_restore (&ada_yydebug, par_state->debug); - lexer_init (ada_yyin); /* (Re-)initialize lexer. */ - int result = ada_yyparse (); if (!result) { @@ -1349,3 +2152,19 @@ ada_parse (struct parser_state *par_state) } return result; } + +INIT_GDB_FILE (ada_exp_parser) +{ + int code = regcomp (&number_regex, number_regex_text, + REG_EXTENDED | REG_ICASE); + /* If the regular expression was incorrect, it was a programming + error. */ + gdb_assert (code == 0); + code = regcomp (&operator_regex, operator_regex_text, + REG_EXTENDED | REG_ICASE); + gdb_assert (code == 0); + +#if GDB_SELF_TEST + selftests::register_test ("ada-lex", ada_exp_parser::selftests::ada_lex_tests); +#endif +} diff --git a/gdb/ada-exp-parser.h b/gdb/ada-exp-parser.h index 09a716e6636..682d868d528 100644 --- a/gdb/ada-exp-parser.h +++ b/gdb/ada-exp-parser.h @@ -23,9 +23,6 @@ #include "ada-exp.h" #include "parser-defs.h" -/* The character we use to represent the completion point. */ -constexpr char COMPLETE_CHAR = '\001'; - namespace ada_exp_parser { @@ -64,18 +61,86 @@ struct ada_parse_state auto_obstack temp_space; - /* Depth of parentheses, used by the lexer. */ - int paren_depth = 0; - - /* When completing, we'll return a special character at the end of the - input, to signal the completion position to the lexer. This is - done because flex does not have a generally useful way to detect - EOF in a pattern. This variable records whether the special - character has been emitted. */ - bool returned_complete = false; + /* Lex a single token. ada_yylval is updated if needed. The token + value is returned. The lexer state in this object or in the + parser_state object will be updated as appropriate. */ + int lex (); private: + /* A lexer helper function to lex a number. */ + int lex_number (); + + /* A lexer helper function to lex a dollar variable like $x or + $$. */ + int lex_dollar (); + + /* A lexer helper that is called when a '.' is seen. */ + int lex_dot (); + + /* A lexer helper that is called when a single quote is seen. */ + int lex_single_quote (); + + /* A lexer helper for lexing a string. */ + int lex_double_quote (); + + /* A helper function that examines TEXT. If TEXT looks like a + simple identifier, a pointer to the character past the end of the + identifier is returned. Otherwise, nullptr is returned. */ + const char *lex_simple_identifier (const char *text); + + /* A helper that does some extra checking for the "thread" + pseudo-keyword. It returns true if this instance of "thread" + should be reported as an EOF rather than an identifier. TEXT + points to just past the end of the "thread" keyword. */ + bool check_thread_keyword (const char *text); + + /* Check whether the current token, held at pstate->lexptr with + length LEN, is a keyword. Returns the token value if so; returns + nullopt if not. */ + std::optional check_keyword (size_t len); + + /* Check whether BRACKET holds text matching a hex character as + would be seen in an Ada string or character literal. If so, + returns a pointer to the character just past the end of the form; + otherwise returns nullptr. */ + const char *recognize_encoded_char (const char *bracket); + + /* A lexer helper for lexing an identifier. */ + int lex_identifier (const char *id_end); + + /* A helper that examines START. If this is a quoted operator name + (like "mod" or "+"), returns a pointer to just after the final + quote. Otherwise, returns nullptr. */ + const char *lex_operator (const char *start); + + /* Return the syntactic code corresponding to the attribute name or + abbreviation STR. COMPLETING should be true if the name was + lexed at the end of the input and completion is enabled for this + parse. */ + int process_attribute (const std::string &str, bool completing); + + /* Return a canonicalized version of NAME0. The + resulting string is valid until the next call to ada_parse. If + NAME0 contains the substring "___", it is assumed to be already + encoded and the resulting name is equal to it. Similarly, if the name + starts with '<', it is copied verbatim. Otherwise, it differs + from NAME0 in that: + + Characters between '...' are transferred verbatim to yylval.ssym. + + Trailing "'" characters in quoted sequences are removed (a leading quote is + preserved to indicate that the name is not to be GNAT-encoded). + + Unquoted whitespace is removed. + + Unquoted alphabetic characters are mapped to lower case. + Result is returned as a struct stoken, but for convenience, the string + is also null-terminated. Result string valid until the next call of + ada_parse. + */ + stoken process_id (std::string_view name0); + + /* Throw an exception when lexing, indicating that an invalid + character was seen. */ + [[noreturn]] void invalid_char (); + /* We don't have a good way to manage non-POD data in Yacc, so store values here. The storage here is only valid for the duration of the parse. */ @@ -83,6 +148,15 @@ struct ada_parse_state /* The original expression string. */ const char *m_original_expr; + + /* Depth of parentheses, used by the lexer. */ + int m_paren_depth = 0; + + /* This holds some state needed when lexing a single quote. + Normally, a single quote will introduce a character literal. + However, after an identifier, it will not, to support cases like + Char_Enum_Type'('B'); see char_enum.exp for examples. */ + bool m_before_qual_quote = false; }; /* Expression completer for attributes. */ @@ -110,17 +184,6 @@ extern struct parser_state *pstate; extern struct ada_parse_state *ada_parser; -/* Initialize the lexer for processing new expression. - - This function is implemented in ada-lex.l, because it needs to see some - macros in ada-lex-gen.c. */ - -void lexer_init (FILE *inp); - -/* Copy S2 to S1, removing all underscores, and downcasing all letters. */ - -void canonicalizeNumeral (char *s1, const char *s2); - /* Return TEXT[0..LEN-1], a string literal without surrounding quotes, with special hex character notations replaced with characters. Result valid until the next call to ada_parse. */ @@ -142,48 +205,6 @@ int processInt (parser_state *par_state, const char *base0, const char *num0, int processReal (struct parser_state *par_state, const char *num0); -/* Store a canonicalized version of NAME0[0..LEN-1] in yylval.ssym. The - resulting string is valid until the next call to ada_parse. If - NAME0 contains the substring "___", it is assumed to be already - encoded and the resulting name is equal to it. Similarly, if the name - starts with '<', it is copied verbatim. Otherwise, it differs - from NAME0 in that: - + Characters between '...' are transferred verbatim to yylval.ssym. - + Trailing "'" characters in quoted sequences are removed (a leading quote is - preserved to indicate that the name is not to be GNAT-encoded). - + Unquoted whitespace is removed. - + Unquoted alphabetic characters are mapped to lower case. - Result is returned as a struct stoken, but for convenience, the string - is also null-terminated. Result string valid until the next call of - ada_parse. - */ - -stoken processId (const char *name0, int len); - -/* Return the syntactic code corresponding to the attribute name or - abbreviation STR. */ - -int processAttribute (const char *str); - -/* Returns the position within STR of the '.' in a - '.{WHITE}*all' component of a dotted name, or -1 if there is none. - Note: we actually don't need this routine, since 'all' can never be an - Ada identifier. Thus, looking up foo.all or foo.all.x as a name - must fail, and will eventually be interpreted as (foo).all or - (foo).all.x. However, this does avoid an extraneous lookup. */ - -int find_dot_all (const char *str); - -/* Back up lexptr by yyleng and then to the rightmost occurrence of - character CH, case-folded (there must be one). WARNING: since - lexptr points to the next input character that Flex has not yet - transferred to its internal buffer, the use of this function - depends on the assumption that Flex calls YY_INPUT only when it is - logically necessary to do so (thus, there is no reading ahead - farther than needed to identify the next token.) */ - -void rewind_to_char (int ch); - /* Like parser_state::pop, but handles Ada type resolution. DEPROCEDURE_P and CONTEXT_TYPE are passed to the resolve method, if called. */ diff --git a/gdb/ada-exp-parser.y b/gdb/ada-exp-parser.y index d37ab12c3bc..6c56c9bf970 100644 --- a/gdb/ada-exp-parser.y +++ b/gdb/ada-exp-parser.y @@ -50,7 +50,11 @@ using namespace expr; using namespace ada_exp_parser; -static int yylex (void); +static int +yylex () +{ + return ada_parser->lex (); +} %} @@ -834,8 +838,3 @@ primary : '*' primary %prec '.' ; %% - -/* yylex defined in ada-lex-gen.c: Reads one token, getting characters */ -/* through lexptr. */ - -#include "ada-lex-gen.c" diff --git a/gdb/ada-lex.l b/gdb/ada-lex.l deleted file mode 100644 index 857176c4d83..00000000000 --- a/gdb/ada-lex.l +++ /dev/null @@ -1,346 +0,0 @@ -/* FLEX lexer for Ada expressions, for GDB. -*- c++ -*- - Copyright (C) 1994-2026 Free Software Foundation, Inc. - - This file is part of GDB. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . */ - -/*----------------------------------------------------------------------*/ - -/* The converted version of this file is to be included in ada-exp-parser.y, */ -/* the Ada parser for gdb. The function yylex obtains characters from */ -/* the global pointer lexptr. It returns a syntactic category for */ -/* each successive token and places a semantic value into yylval */ -/* (ada-lval), defined by the parser. */ - -DIG [0-9] -NUM10 ({DIG}({DIG}|_)*) -HEXDIG [0-9a-f] -NUM16 ({HEXDIG}({HEXDIG}|_)*) -OCTDIG [0-7] -LETTER [a-z_] -ID ({LETTER}({LETTER}|{DIG}|[\x80-\xff])*|"<"{LETTER}({LETTER}|{DIG})*">") -WHITE [ \t\n] -TICK ("'"{WHITE}*) -GRAPHIC [a-z0-9 #&'()*+,-./:;<>=_|!$%?@\[\]\\^`{}~] -OPER ([-+*/=<>&]|"<="|">="|"**"|"/="|"and"|"or"|"xor"|"not"|"mod"|"rem"|"abs") - -EXP (e[+-]{NUM10}) -POSEXP (e"+"?{NUM10}) - -/* This must agree with COMPLETE_CHAR in ada-exp-parser.h. See the - comment on ada_parse_state::returned_complete for the explanation. */ -COMPLETE "\001" -NOT_COMPLETE [^\001] - -%{ - -#include "diagnostics.h" - -/* Some old versions of flex (2.5.x) generate code that uses the "register" - keyword, which compilers warn about, because it is not allowed in ISO - C++17. */ -DIAGNOSTIC_PUSH -DIAGNOSTIC_IGNORE_REGISTER - -#define NUMERAL_WIDTH 256 -#define LONGEST_SIGN ((ULONGEST) 1 << (sizeof(LONGEST) * HOST_CHAR_BIT - 1)) - -#undef YY_DECL -#define YY_DECL static int yylex ( void ) - -/* Flex generates a static function "input" which is not used. - Defining YY_NO_INPUT comments it out. */ -#define YY_NO_INPUT - -#undef YY_INPUT -#define YY_INPUT(BUF, RESULT, MAX_SIZE) \ - if ( *pstate->lexptr == '\000' ) \ - { \ - if (pstate->parse_completion && !ada_parser->returned_complete) \ - { \ - ada_parser->returned_complete = true; \ - *(BUF) = COMPLETE_CHAR; \ - (RESULT) = 1; \ - } \ - else \ - (RESULT) = YY_NULL; \ - } \ - else \ - { \ - *(BUF) = *pstate->lexptr == COMPLETE_CHAR ? ' ' : *pstate->lexptr; \ - (RESULT) = 1; \ - pstate->lexptr += 1; \ - } - -%} - -%option case-insensitive interactive nodefault noyywrap - -%s BEFORE_QUAL_QUOTE - -%% - -{WHITE} { } - -"--".* { yyterminate(); } - -{NUM10}{POSEXP} { - char numbuf[NUMERAL_WIDTH]; - canonicalizeNumeral (numbuf, yytext); - char *e_ptr = strrchr (numbuf, 'e'); - *e_ptr = '\0'; - return processInt (pstate, nullptr, numbuf, e_ptr + 1); - } - -{NUM10} { - char numbuf[NUMERAL_WIDTH]; - canonicalizeNumeral (numbuf, yytext); - return processInt (pstate, NULL, numbuf, NULL); - } - -{NUM10}"#"{HEXDIG}({HEXDIG}|_)*"#"{POSEXP} { - char numbuf[NUMERAL_WIDTH]; - canonicalizeNumeral (numbuf, yytext); - char *e_ptr = strrchr (numbuf, 'e'); - *e_ptr = '\0'; - return processInt (pstate, numbuf, - strchr (numbuf, '#') + 1, - e_ptr + 1); - } - - /* The "llf" is a gdb extension to allow a floating-point - constant to be written in some other base. The - floating-point number is formed by reinterpreting the - bytes, allowing direct control over the bits. */ -{NUM10}(l{0,2}f)?"#"{HEXDIG}({HEXDIG}|_)*"#" { - char numbuf[NUMERAL_WIDTH]; - canonicalizeNumeral (numbuf, yytext); - return processInt (pstate, numbuf, strchr (numbuf, '#') + 1, - NULL); - } - -"0x"{HEXDIG}+ { - char numbuf[NUMERAL_WIDTH]; - canonicalizeNumeral (numbuf, yytext+2); - return processInt (pstate, "16#", numbuf, NULL); - } - - -{NUM10}"."{NUM10}{EXP} { - char numbuf[NUMERAL_WIDTH]; - canonicalizeNumeral (numbuf, yytext); - return processReal (pstate, numbuf); - } - -{NUM10}"."{NUM10} { - char numbuf[NUMERAL_WIDTH]; - canonicalizeNumeral (numbuf, yytext); - return processReal (pstate, numbuf); - } - -{NUM10}"#"{NUM16}"."{NUM16}"#"{EXP} { - error (_("Based real literals not implemented yet.")); - } - -{NUM10}"#"{NUM16}"."{NUM16}"#" { - error (_("Based real literals not implemented yet.")); - } - -"'"({GRAPHIC}|\")"'" { - yylval.typed_char.val = yytext[1]; - yylval.typed_char.type = type_for_char (pstate, yytext[1]); - return CHARLIT; - } - -"'[\""{HEXDIG}{2,}"\"]'" { - ULONGEST v = strtoulst (yytext+3, nullptr, 16); - yylval.typed_char.val = v; - yylval.typed_char.type = type_for_char (pstate, v); - return CHARLIT; - } - - /* Note that we don't handle bracket sequences of more than 2 - digits here. Currently there's no support for wide or - wide-wide strings. */ -\"({GRAPHIC}|"[\""({HEXDIG}{2,}|\")"\"]")*\" { - yylval.sval = processString (yytext+1, yyleng-2); - return STRING; - } - -\" { - error (_("ill-formed or non-terminated string literal")); - } - - -if { - rewind_to_char ('i'); - return 0; - } - -task { - rewind_to_char ('t'); - return 0; - } - -thread{WHITE}+{DIG} { - /* This keyword signals the end of the expression and - will be processed separately. */ - rewind_to_char ('t'); - return 0; - } - - /* ADA KEYWORDS */ - -abs { return ABS; } -and { return _AND_; } -delta { return DELTA; } -else { return ELSE; } -for { return FOR; } -in { return IN; } -mod { return MOD; } -new { return NEW; } -not { return NOT; } -null { return NULL_PTR; } -or { return OR; } -others { return OTHERS; } -rem { return REM; } -then { return THEN; } -with { return WITH; } -xor { return XOR; } - - /* BOOLEAN "KEYWORDS" */ - - /* True and False are not keywords in Ada, but rather enumeration constants. - However, the boolean type is no longer represented as an enum, so True - and False are no longer defined in symbol tables. We compromise by - making them keywords (when bare). */ - -true { return TRUEKEYWORD; } -false { return FALSEKEYWORD; } - - /* ATTRIBUTES */ - -{TICK}([a-z][a-z_]*)?{COMPLETE}? { BEGIN INITIAL; return processAttribute (yytext); } - - /* PUNCTUATION */ - -"=>" { return ARROW; } -".." { return DOTDOT; } -"**" { return STARSTAR; } -":=" { return ASSIGN; } -"/=" { return NOTEQUAL; } -"<=" { return LEQ; } -">=" { return GEQ; } - -"'"/{NOT_COMPLETE} { BEGIN INITIAL; return '\''; } - -[-&*+{}@/:<>=|;\[\]] { return yytext[0]; } - -"," { if (ada_parser->paren_depth == 0 && pstate->comma_terminates) - { - rewind_to_char (','); - return 0; - } - else - return ','; - } - -"(" { ada_parser->paren_depth += 1; return '('; } -")" { if (ada_parser->paren_depth == 0) - { - rewind_to_char (')'); - return 0; - } - else - { - ada_parser->paren_depth -= 1; - return ')'; - } - } - -"."{WHITE}*{ID}{COMPLETE}? { - yylval.sval = processId (yytext+1, yyleng-1); - if (yytext[yyleng - 1] == COMPLETE_CHAR) - return DOT_COMPLETE; - return DOT_ID; - } - -"."{WHITE}*{COMPLETE} { - yylval.sval.ptr = ""; - yylval.sval.length = 0; - return DOT_COMPLETE; - } - -{ID}({WHITE}*"."{WHITE}*({ID}|\"{OPER}\"))*(" "*"'"|{COMPLETE})? { - int all_posn = find_dot_all (yytext); - - if (all_posn == -1 && yytext[yyleng-1] == '\'') - { - BEGIN BEFORE_QUAL_QUOTE; - yyless (yyleng-1); - } - else if (all_posn >= 0) - yyless (all_posn); - bool is_completion = yytext[yyleng - 1] == COMPLETE_CHAR; - yylval.sval = processId (yytext, yyleng); - return is_completion ? NAME_COMPLETE : NAME; - } - - - /* GDB EXPRESSION CONSTRUCTS */ - -"'"[^']+"'"{WHITE}*:: { - yyless (yyleng - 2); - yylval.sval = processId (yytext, yyleng); - return NAME; - } - -"::" { return COLONCOLON; } - - /* REGISTERS AND GDB CONVENIENCE VARIABLES */ - -"$"({LETTER}|{DIG}|"$")* { - yylval.sval.ptr = yytext; - yylval.sval.length = yyleng; - return DOLLAR_VARIABLE; - } - - /* CATCH-ALL ERROR CASE */ - -. { error (_("Invalid character '%s' in expression."), yytext); } -%% - -namespace ada_exp_parser -{ - -/* See ada-exp-parser.h. */ - -void -lexer_init (FILE *inp) -{ - BEGIN INITIAL; - yyrestart (inp); -} - -} /* namespace ada_exp_parser */ - -/* Dummy definition to suppress warnings about unused static definitions. */ -typedef void (*dummy_function) (); -dummy_function ada_flex_use[] = -{ - (dummy_function) yyunput -}; - -DIAGNOSTIC_POP base-commit: f318ccd4761fb960a9584a404be3c61e5405f077 -- 2.56.0